import { PrismaClient, UserRole } from '@prisma/client';

const prisma = new PrismaClient();

async function seedReviews() {
  try {
    console.log('Starting to seed reviews...');

    // Create some sample users if they don't exist
    const freelancer = await prisma.user.upsert({
      where: { email: 'freelancer@example.com' },
      update: {},
      create: {
        email: 'freelancer@example.com',
        role: UserRole.FREELANCER,
        status: true,
        profile: {
          create: {
            firstName: 'John',
            lastName: 'Doe',
            countryId: 'switzerland', // Switzerland
            bio: 'Experienced freelancer'
          }
        }
      }
    });

    const client1 = await prisma.user.upsert({
      where: { email: 'client1@example.com' },
      update: {},
      create: {
        email: 'client1@example.com',
        role: UserRole.CLIENT,
        status: true,
        profile: {
          create: {
            firstName: 'Sarah',
            lastName: 'Johnson',
            countryId: 'switzerland'
          }
        }
      }
    });

    const client2 = await prisma.user.upsert({
      where: { email: 'client2@example.com' },
      update: {},
      create: {
        email: 'client2@example.com',
        role: UserRole.CLIENT,
        status: true,
        profile: {
          create: {
            firstName: 'Michael',
            lastName: 'Smith',
            countryId: 'switzerland'
          }
        }
      }
    });

    // Create a sample category
    const category = await prisma.category.upsert({
      where: { slug: 'web-development' },
      update: {},
      create: {
        name: 'Web Development',
        slug: 'web-development',
        description: 'Web development projects'
      }
    });

    // Create sample projects
    const project1 = await prisma.project.upsert({
      where: { id: 'sample-project-1' },
      update: {},
      create: {
        id: 'sample-project-1',
        title: 'E-commerce Website Development',
        description: 'Need a modern e-commerce website with payment integration',
        budget: 2500.00,
        duration: 30,
        clientId: client1.id,
        categoryId: category.id,
        countryId: 'switzerland',
        status: 'COMPLETED'
      }
    });

    const project2 = await prisma.project.upsert({
      where: { id: 'sample-project-2' },
      update: {},
      create: {
        id: 'sample-project-2',
        title: 'Mobile App Design',
        description: 'UI/UX design for a mobile application',
        budget: 1800.00,
        duration: 21,
        clientId: client2.id,
        categoryId: category.id,
        countryId: 'switzerland',
        status: 'COMPLETED'
      }
    });

    // Create sample reviews - both directions
    const reviews = [
      // Client reviews about freelancer
      {
        rating: 5,
        comment: 'Excellent work! Very professional and delivered on time. Great communication throughout the project.',
        authorId: client1.id,
        recipientId: freelancer.id,
        projectId: project1.id
      },
      {
        rating: 4,
        comment: 'Good quality work and responsive to feedback. Would recommend.',
        authorId: client2.id,
        recipientId: freelancer.id,
        projectId: project2.id
      },
      // Freelancer reviews about clients
      {
        rating: 5,
        comment: 'Great client to work with! Clear requirements, prompt payments, and excellent communication.',
        authorId: freelancer.id,
        recipientId: client1.id,
        projectId: project1.id
      },
      {
        rating: 4,
        comment: 'Professional client with clear expectations. Payment was prompt and feedback was constructive.',
        authorId: freelancer.id,
        recipientId: client2.id,
        projectId: project2.id
      },
      {
        rating: 5,
        comment: 'Highly recommended client! Very organized and respectful throughout the project.',
        authorId: freelancer.id,
        recipientId: client1.id,
        projectId: project1.id
      }
    ];

    // Insert reviews
    for (const reviewData of reviews) {
      await prisma.review.create({
        data: reviewData
      });
    }

    console.log('✅ Reviews seeded successfully!');
    
    // Separate freelancer and client reviews
    const freelancerReviews = reviews.filter(r => r.recipientId === freelancer.id);
    const clientReviews = reviews.filter(r => r.recipientId === client1.id || r.recipientId === client2.id);
    
    console.log(`Created ${freelancerReviews.length} reviews for freelancer ${freelancer.email}`);
    console.log(`Created ${clientReviews.length} reviews for clients`);
    
    // Calculate average ratings
    if (freelancerReviews.length > 0) {
      const avgFreelancerRating = freelancerReviews.reduce((sum, r) => sum + r.rating, 0) / freelancerReviews.length;
      console.log(`Freelancer average rating: ${avgFreelancerRating.toFixed(1)} (${freelancerReviews.length} reviews)`);
    }
    
    if (clientReviews.length > 0) {
      const avgClientRating = clientReviews.reduce((sum, r) => sum + r.rating, 0) / clientReviews.length;
      console.log(`Client average rating: ${avgClientRating.toFixed(1)} (${clientReviews.length} reviews)`);
    }

  } catch (error) {
    console.error('Error seeding reviews:', error);
  } finally {
    await prisma.$disconnect();
  }
}

// Run if called directly
if (require.main === module) {
  seedReviews()
    .catch((e) => {
      console.error(e);
      process.exit(1);
    });
}

export { seedReviews };