/**
 * Adds two visitors created via the new "Manual entry" toggle on the
 * Add Visitor page. Manual entries skip the check-in policy entirely:
 *   - requiresApproval = false
 *   - assignedApproverId = null
 *   - status stays EXPECTED (no approval awaited)
 * QR/shortId are still generated so the row is shape-compatible with
 * existing tooling, but reception won't surface or scan them.
 *
 * Run with: npx ts-node -r dotenv/config src/scripts/manualEntries.ts
 */

import { nanoid } from 'nanoid';
import { prisma } from '../config/database';
import { generateQRCodeBuffer } from '../utils/qrcode';
import { saveUpload } from '../config/storage';

async function mkVisitorBase(): Promise<{ shortId: string; qrCodeUrl: string }> {
  const shortId = nanoid(10).toUpperCase();
  const buf = await generateQRCodeBuffer(shortId);
  const url = await saveUpload(buf, `visitors/qr/${shortId}.png`, 'image/png');
  return { shortId, qrCodeUrl: url };
}

async function main(): Promise<void> {
  const owner = await prisma.owner.findFirst({ where: { email: 'owner@example.com' } });
  if (!owner) throw new Error('Run `npm run seed` first — owner@example.com not found.');

  // Clear any prior runs of THIS script so we don't accumulate duplicates while
  // iterating. Targets only the two demo names so other test data stays put.
  await prisma.visitor.deleteMany({
    where: {
      ownerId: owner.id,
      name: { in: ['Rahul Mehta', 'Anita Desai'] },
    },
  });

  const today = new Date();
  const todayStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;

  const rows = [
    {
      name: 'Rahul Mehta',
      email: 'rahul.mehta@acmeholdings.com',
      mobile: '+91 98123 45678',
      reasonForVisit: 'Investor briefing',
      notes: 'Founder of Acme Holdings — long-standing partner, escort directly to MD\'s office. No QR / approval needed.',
      visitDate: todayStr,
      visitTime: '11:00',
    },
    {
      name: 'Anita Desai',
      email: 'anita@desailegal.in',
      mobile: '+91 90876 54321',
      reasonForVisit: 'Document handover',
      notes: 'Personal counsel for the founder. Drops off contracts every Tuesday — recognise on sight.',
      visitDate: todayStr,
      visitTime: '15:30',
    },
  ];

  const now = new Date();
  for (const r of rows) {
    const { shortId, qrCodeUrl } = await mkVisitorBase();
    const visitor = await prisma.visitor.create({
      data: {
        ownerId: owner.id,
        shortId,
        name: r.name,
        email: r.email,
        mobile: r.mobile,
        reasonForVisit: r.reasonForVisit,
        notes: r.notes,
        visitDate: new Date(`${r.visitDate}T${r.visitTime}:00`),
        visitTime: r.visitTime,
        qrCodeUrl,
        isManualEntry: true,
        status: 'ARRIVED',
        arrivedAt: now,
        requiresApproval: false,
        assignedApproverId: null,
      },
    });
    console.log(`[manualEntries] created ${visitor.name} — shortId=${visitor.shortId} status=${visitor.status} isManualEntry=${visitor.isManualEntry}`);
  }
}

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