import { PrismaClient } from '@prisma/client';
import { PrismaPg } from '@prisma/adapter-pg';
import pg from 'pg';
import dotenv from 'dotenv';

dotenv.config({ path: '.env.local' });
dotenv.config();

const connectionString = process.env.DATABASE_URL!;
const pool = new pg.Pool({ connectionString });
const adapter = new PrismaPg(pool);
const prisma = new PrismaClient({ adapter });

async function migrate() {
  console.log('--- Starting isActive Migration ---');
  
  const businesses = await prisma.business.findMany();
  console.log(`Found ${businesses.length} businesses to check.`);
  
  let updatedCount = 0;
  
  for (const biz of businesses) {
    const isNameOk = biz.name && biz.name !== "Nouvelle Entreprise";
    const isDescOk = biz.description && biz.description.length >= 20;
    const isLocOk = biz.location && biz.location !== "Ma Ville";
    const isEmailOk = !!biz.contactEmail;
    const isPhoneOk = !!biz.contactPhone;

    const newIsActive = !!(isNameOk && isDescOk && isLocOk && isEmailOk && isPhoneOk);
    
    if (biz.isActive !== newIsActive) {
      await prisma.business.update({
        where: { id: biz.id },
        data: { isActive: newIsActive }
      });
      console.log(`Updated "${biz.name}" (ID: ${biz.id}): isActive ${biz.isActive} -> ${newIsActive}`);
      updatedCount++;
    }
  }
  
  console.log(`--- Migration Complete: ${updatedCount} records updated ---`);
}

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