const { PrismaClient } = require('@prisma/client');
const { v4: uuidv4 } = require('uuid');

const prisma = new PrismaClient();

async function syncLeadsToPipeline() {
  console.log('--- Syncing Quality/Potential Clients to Pipeline ---');
  
  // Find clients with statuses that should be in the pipeline
  const clients = await prisma.client.findMany({
    where: {
      status: { in: ['QUALITY', 'POTENTIAL', 'DEMO', 'SALES', 'CLOSED'] }
    },
    include: {
      opportunities: true
    }
  });

  console.log(`Found ${clients.length} clients with relevant status.`);

  const stageMap = {
    'QUALITY': 'QUALIFIED',
    'POTENTIAL': 'POTENTIAL',
    'DEMO': 'DEMO',
    'SALES': 'WON',
    'CLOSED': 'WON'
  };

  let createdCount = 0;
  let updatedCount = 0;

  for (const client of clients) {
    const targetStage = stageMap[client.status];
    if (!targetStage) continue;

    // Check if they already have an active opportunity
    const activeOpp = client.opportunities.find(o => !['WON', 'LOST'].includes(o.stage));

    if (activeOpp) {
      if (activeOpp.stage !== targetStage) {
        await prisma.opportunity.update({
          where: { id: activeOpp.id },
          data: { stage: targetStage }
        });
        updatedCount++;
      }
    } else {
      // Check if they have a WON opportunity if status is SALES/CLOSED
      const wonOpp = client.opportunities.find(o => o.stage === 'WON');
      if (wonOpp) continue;

      // Create new opportunity
      await prisma.opportunity.create({
        data: {
          id: uuidv4(),
          title: `${client.name} - ${client.status}`,
          value: 0,
          clientId: client.id,
          assignedTo: client.assignedTo || '805c8cf3-db7c-47c3-b42e-588531ba89a1', // Default to Admin if no owner
          stage: targetStage,
          updatedAt: new Date()
        }
      });
      createdCount++;
    }
  }

  console.log(`Finished: Created ${createdCount} and updated ${updatedCount} opportunities.`);
}

syncLeadsToPipeline()
  .catch(e => console.error(e))
  .finally(() => prisma.$disconnect());
