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 {
  // Only ACTIVE dealers — skip cancelled/payment_failed (5 of them).
  // For each: enqueue ONE verify_property. The worker chains verify → register → submit_sitemap.
  const dealers = await prisma.dealer.findMany({
    where: {
      customDomain: { not: null },
      AND: [{ customDomain: { not: '' } }],
      customDomainStatus: 'active',
      status: 'active',
      gscPropertyRegisteredAt: null,
      gscJobs: {
        none: {
          type: 'verify_property',
          status: { in: ['pending', 'running', 'completed'] },
        },
      },
    },
    select: { id: true, customDomain: true, subdomain: true },
  });

  console.log(`Enqueuing verify_property for ${dealers.length} active orphan custom-domain dealers...\n`);

  const result = await prisma.gscJob.createMany({
    data: dealers.map(d => ({
      type: 'verify_property',
      dealerId: d.id,
      priority: 50,
      payload: { propertyHost: d.customDomain },
    })),
  });

  console.log(`Enqueued: ${result.count} jobs\n`);

  const counts = await prisma.gscJob.groupBy({
    by: ['type', 'status'],
    _count: true,
    orderBy: [{ type: 'asc' }, { status: 'asc' }],
  });
  console.log('=== queue depth after enqueue ===');
  for (const c of counts) console.log(`${c.type.padEnd(20)} ${c.status.padEnd(10)} ${c._count}`);
} finally {
  await prisma.$disconnect();
  await pool.end();
}
