import { prisma } from '../config/database';

// Visitor passes default to 24 hours from issue when the user didn't pick a
// specific expiry. Keeps the system honest — without an expiry a pass could
// linger forever and skew the scanner's reports.
export const DEFAULT_PASS_DURATION_MS = 24 * 60 * 60 * 1000;

export function defaultExpiry(now: Date = new Date()): Date {
  return new Date(now.getTime() + DEFAULT_PASS_DURATION_MS);
}

// Flips any EXPECTED / AWAITING_APPROVAL visitors whose expiresAt has gone by
// to EXPIRED — the pass's validity window has closed. This is distinct from the
// no-show auto-cancel sweep (visit date passed → CANCELLED); a lapsed pass is
// "Expired", not "Cancelled". Called lazily from read endpoints (list visitors,
// owner counts, etc.) so we don't need a background cron. Idempotent — a row
// that already ARRIVED, REJECTED, or has no expiresAt is left alone. Mirrors
// the scanner's on-scan lazy-expiry, which already flips to EXPIRED.
export async function expireOverdueVisitors(ownerId: string): Promise<number> {
  const result = await prisma.visitor.updateMany({
    where: {
      ownerId,
      status: { in: ['EXPECTED', 'AWAITING_APPROVAL'] },
      expiresAt: { not: null, lt: new Date() },
    },
    data: { status: 'EXPIRED' },
  });
  return result.count;
}
