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 {
  const jobs = await prisma.gscJob.findMany({
    where: { dealer: { subdomain: { in: ['coastwideoil', 'jacks5'] } } },
    orderBy: [{ dealer: { subdomain: 'asc' } }, { createdAt: 'asc' }],
    select: {
      id: true, type: true, status: true, attempts: true,
      runAt: true, startedAt: true, completedAt: true, lastError: true,
      dealer: { select: { subdomain: true, customDomain: true, gscVerificationToken: true } },
    },
  });

  const byDealer = {};
  for (const j of jobs) {
    const sub = j.dealer.subdomain;
    if (!byDealer[sub]) {
      byDealer[sub] = {
        tokenPreview: j.dealer.gscVerificationToken ? j.dealer.gscVerificationToken.slice(0, 40) + '...' : 'NULL',
        customDomain: j.dealer.customDomain,
        jobs: [],
      };
    }
    byDealer[sub].jobs.push(j);
  }

  for (const [sub, info] of Object.entries(byDealer)) {
    console.log('\n=== ' + sub + ' (' + info.customDomain + ') ===');
    console.log('token: ' + info.tokenPreview);
    for (const j of info.jobs) {
      console.log('  [' + j.status.padEnd(9) + '] ' + j.type.padEnd(20) + ' attempts=' + j.attempts + ' runAt=' + (j.runAt ? j.runAt.toISOString() : '-'));
      if (j.lastError) console.log('    lastError: ' + j.lastError.slice(0, 120));
    }
  }
} finally {
  await prisma.$disconnect();
  await pool.end();
}
