/**
 * One-off: create 50 test bugs for kanban / scroll testing.
 * Usage: npx tsx scripts/seed-test-bugs.ts
 */
import { BugSeverity, BugStatus, PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

const STATUSES: BugStatus[] = [
  BugStatus.Open,
  BugStatus.Assigned,
  BugStatus.InProgress,
  BugStatus.ReadyForRetest,
  BugStatus.Reopened,
  BugStatus.Closed,
];

const SEVERITIES: BugSeverity[] = [
  BugSeverity.Critical,
  BugSeverity.High,
  BugSeverity.Medium,
  BugSeverity.Low,
];

const TITLES = [
  'Login button unresponsive on mobile',
  'Session timeout without warning',
  'Kanban cards overlap on resize',
  'Filter chips not clearing',
  'Timesheet total mismatch',
  'Attachment preview blank for PDF',
  'Assignee avatar missing color',
  'Stage chevron skips Gate B check',
  'Notification badge stuck at zero',
  'Search ignores project code',
  'Deadline shows wrong timezone',
  'Subtask count incorrect',
  'Priority stars not saving',
  'Chatter note duplicates',
  'QA evidence upload fails',
  'Bug status rollback error',
  'Member allocation modal empty',
  'Export CSV truncates titles',
  'Dark mode contrast issue',
  'Breadcrumb link 404',
];

async function nextBugCode(): Promise<string> {
  const row = await prisma.idCounter.upsert({
    where: { key: 'bug' },
    create: { key: 'bug', value: 1 },
    update: { value: { increment: 1 } },
  });
  return `BUG-${String(row.value).padStart(3, '0')}`;
}

async function main() {
  const tasks = await prisma.task.findMany({
    where: { parentId: null },
    select: { id: true, code: true },
    take: 40,
  });
  if (!tasks.length) {
    throw new Error('No parent tasks found. Run seed first.');
  }

  const employees = await prisma.employee.findMany({
    where: { active: true },
    select: { id: true, code: true },
  });
  if (!employees.length) {
    throw new Error('No employees found. Run seed first.');
  }

  const reporter =
    employees.find((e) => e.code === 'EMP-001') ||
    employees.find((e) => e.code === 'EMP-005') ||
    employees[0];

  const before = await prisma.bug.count();
  const created: string[] = [];

  for (let i = 0; i < 50; i++) {
    const task = tasks[i % tasks.length];
    const assignee = employees[i % employees.length];
    const status = STATUSES[i % STATUSES.length];
    const severity = SEVERITIES[i % SEVERITIES.length];
    const hours = [1, 2, 3, 4, 6, 8][i % 6];
    const title = `${TITLES[i % TITLES.length]} #${i + 1}`;
    const code = await nextBugCode();

    await prisma.bug.create({
      data: {
        code,
        parentTaskId: task.id,
        title,
        description: `Test bug ${i + 1} for kanban scroll / fold QA.`,
        reproSteps: `1. Open Bugs kanban\n2. Locate ${code}\n3. Verify column layout`,
        expected: 'Card visible in correct status column',
        actual: 'N/A — synthetic test data',
        severity,
        priority: i % 4,
        assigneeId: assignee.id,
        reporterId: reporter.id,
        allocatedHours: hours,
        blocking: i % 7 === 0,
        status,
        resolutionNotes: status === BugStatus.Closed ? 'Closed in test seed' : '',
        assignments: {
          create: [{ employeeId: assignee.id, allocatedHours: hours }],
        },
      },
    });
    created.push(code);
  }

  const after = await prisma.bug.count();
  console.log(`Created ${created.length} bugs (${before} → ${after}).`);
  console.log(`First: ${created[0]}, Last: ${created[created.length - 1]}`);
  console.log(
    'By status approx: ' +
      STATUSES.map((s) => `${s}≈${Math.ceil(50 / STATUSES.length)}`).join(', ')
  );
}

main()
  .catch((err) => {
    console.error(err);
    process.exitCode = 1;
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
