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

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

try {
  // Custom-domain dealers that haven't gone through the activation chain.
  const dealers = await prisma.dealer.findMany({
    where: {
      customDomain: { not: null },
      AND: [{ customDomain: { not: '' } }],
      customDomainStatus: 'active',
      gscPropertyRegisteredAt: null,
      gscJobs: {
        none: {
          type: 'verify_property',
          status: { in: ['pending', 'running', 'completed'] },
        },
      },
    },
    select: { id: true, subdomain: true, customDomain: true, status: true },
    orderBy: { customDomain: 'asc' },
  });

  console.log(`Found ${dealers.length} orphan custom-domain dealers ready for activation:\n`);
  for (const d of dealers.slice(0, 10)) {
    console.log(`  ${d.subdomain.padEnd(25)} | ${d.customDomain.padEnd(35)} | dealer_status=${d.status}`);
  }
  if (dealers.length > 10) console.log(`  ... and ${dealers.length - 10} more`);

  console.log(`\n=== distribution by dealer.status ===`);
  const byStatus = {};
  for (const d of dealers) byStatus[d.status] = (byStatus[d.status] || 0) + 1;
  console.log(byStatus);
} finally {
  await prisma.$disconnect();
  await pool.end();
}
