import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { inBackground, notifyVisitorArrived } from '../notifications/notifications.service';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';
import { presignDownload } from '../uploads/uploads.service';
import { paginated, type Pagination } from '../../lib/pagination';

/**
 * Visitors (Sprint 5): logged by the guard at the gate, or pre-registered
 * by the resident so the guard already knows to expect them. Identity is
 * kept to what a register needs — the ID's type and last four digits.
 */

const include = { student: { include: { user: { select: { name: true } }, bed: { include: { room: { select: { number: true } } } } } } } as const;

async function shape(v: { id: string; name: string; phone: string | null; idType: string | null; idLast4: string | null; photoKey: string | null; purpose: string | null; expectedFrom: Date | null; expectedTo: Date | null; inAt: Date | null; outAt: Date | null; status: string; createdAt: Date; studentProfileId: string | null; student: { user: { name: string }; bed: { label: string; room: { number: string } } | null } | null }, withPhoto = false) {
  return {
    id: v.id,
    name: v.name,
    phone: v.phone,
    idType: v.idType,
    idLast4: v.idLast4,
    photoKey: v.photoKey,
    photoUrl: withPhoto && v.photoKey ? await presignDownload(getTenantIdOrThrow(), v.photoKey).catch(() => null) : null,
    purpose: v.purpose,
    expectedFrom: v.expectedFrom,
    expectedTo: v.expectedTo,
    inAt: v.inAt,
    outAt: v.outAt,
    status: v.status,
    createdAt: v.createdAt,
    visiting: v.student ? { id: v.studentProfileId, name: v.student.user.name, room: v.student.bed ? `Room ${v.student.bed.room.number} · Bed ${v.student.bed.label}` : null } : null,
  };
}

export interface VisitorInput {
  name: string;
  phone?: string;
  idType?: string;
  idLast4?: string;
  photoKey?: string;
  purpose?: string;
  studentProfileId?: string;
  expectedFrom?: Date;
  expectedTo?: Date;
}

/** Guard or warden: a visitor at the gate, in now. */
export async function logVisitor(propertyId: string, input: VisitorInput, loggedById: string) {
  const tenantId = getTenantIdOrThrow();
  if (input.studentProfileId) {
    const s = await db.studentProfile.findFirst({ where: { id: input.studentProfileId, propertyId }, select: { id: true } });
    if (!s) throw new NotFoundError('That student is not in this property');
  }
  const row = await db.visitor.create({
    data: { tenantId, propertyId, studentProfileId: input.studentProfileId ?? null, name: input.name.trim(), phone: input.phone?.trim() ?? null, idType: input.idType ?? null, idLast4: input.idLast4 ?? null, photoKey: input.photoKey ?? null, purpose: input.purpose?.trim() ?? null, inAt: new Date(), status: 'IN', loggedById },
    include,
  });
  if (row.studentProfileId) inBackground('push: visitor arrived', () => notifyVisitorArrived(tenantId, row.id));
  return shape(row, true);
}

/** Student: expect someone, within a time window. */
export async function preRegister(userId: string, input: VisitorInput) {
  const tenantId = getTenantIdOrThrow();
  const profile = await db.studentProfile.findFirst({ where: { userId }, select: { id: true, propertyId: true } });
  if (!profile?.propertyId) throw new NotFoundError('No student profile for this account');
  if (!input.expectedFrom || !input.expectedTo) throw new BadRequestError('Say when to expect them');
  if (input.expectedTo <= input.expectedFrom) throw new BadRequestError('The window must end after it starts');
  if (input.expectedTo.getTime() < Date.now()) throw new BadRequestError('That window has already passed');
  const open = await db.visitor.count({ where: { studentProfileId: profile.id, status: 'EXPECTED' } });
  if (open >= 5) throw new ConflictError('You already have 5 visitors expected');
  const row = await db.visitor.create({
    data: { tenantId, propertyId: profile.propertyId, studentProfileId: profile.id, name: input.name.trim(), phone: input.phone?.trim() ?? null, purpose: input.purpose?.trim() ?? null, expectedFrom: input.expectedFrom, expectedTo: input.expectedTo, status: 'EXPECTED', preRegisteredBy: userId },
    include,
  });
  return shape(row);
}

export async function myVisitors(userId: string) {
  const profile = await db.studentProfile.findFirst({ where: { userId }, select: { id: true } });
  if (!profile) throw new NotFoundError('No student profile for this account');
  const rows = await db.visitor.findMany({ where: { studentProfileId: profile.id }, include, orderBy: { createdAt: 'desc' }, take: 30 });
  return Promise.all(rows.map((r) => shape(r)));
}

export async function cancelMyVisitor(userId: string, id: string) {
  const profile = await db.studentProfile.findFirst({ where: { userId }, select: { id: true } });
  const row = await db.visitor.findFirst({ where: { id, studentProfileId: profile?.id ?? '' } });
  if (!row) throw new NotFoundError('Visitor not found');
  if (row.status !== 'EXPECTED') throw new ConflictError('This visitor has already arrived');
  return shape(await db.visitor.update({ where: { id }, data: { status: 'NO_SHOW' }, include }));
}

/** Guard: the pre-registered visitor arrived (or a logged one leaves). */
export async function markArrived(id: string, patch: { idType?: string; idLast4?: string; photoKey?: string; phone?: string }, byUserId: string) {
  const row = await db.visitor.findFirst({ where: { id } });
  if (!row) throw new NotFoundError('Visitor not found');
  if (row.status !== 'EXPECTED') throw new ConflictError(`This visitor is already ${row.status.toLowerCase()}`);
  const arrived = await db.visitor.update({ where: { id }, data: { ...patch, inAt: new Date(), status: 'IN', loggedById: byUserId }, include });
  if (arrived.studentProfileId) {
    const tenantId = getTenantIdOrThrow();
    inBackground('push: visitor arrived', () => notifyVisitorArrived(tenantId, id));
  }
  return shape(arrived, true);
}

export async function markLeft(id: string) {
  const row = await db.visitor.findFirst({ where: { id } });
  if (!row) throw new NotFoundError('Visitor not found');
  if (row.status !== 'IN') throw new ConflictError('This visitor is not inside');
  return shape(await db.visitor.update({ where: { id }, data: { outAt: new Date(), status: 'OUT' }, include }));
}

/** India's day for a date: what the gate's register calls today. */
export const istDay = (now = new Date()) => new Date(now.getTime() + 330 * 60_000).toISOString().slice(0, 10);

/**
 * The register's day (Sprint L4): an India day, midnight to midnight IST. It
 * was a UTC day, so a visitor who came in before 5:30 in the morning fell on
 * the day before.
 */
function dayWhere(propertyId: string | undefined, date: string, status?: string) {
  const start = new Date(Date.parse(`${date}T00:00:00.000Z`) - 330 * 60_000);
  const end = new Date(start.getTime() + 86_400_000);
  return {
    ...(propertyId ? { propertyId } : {}),
    ...(status ? { status } : {}),
    OR: [{ inAt: { gte: start, lt: end } }, { expectedFrom: { gte: start, lt: end } }, { AND: [{ status: 'IN' }, { inAt: { lt: end } }] }],
  };
}

/** The day's register (an India day), everyone expected, in or gone. */
export async function listVisitors(propertyId: string | undefined, date: string, status?: string) {
  const rows = await db.visitor.findMany({
    where: dayWhere(propertyId, date, status),
    include,
    orderBy: [{ inAt: 'desc' }, { expectedFrom: 'asc' }],
    take: 300,
  });
  return Promise.all(rows.map((r) => shape(r, true)));
}

/**
 * The same register a page at a time (Sprint L2), so a busy gate's day never
 * stops at 300. The id breaks ties, or a row could repeat across two pages.
 */
export async function pageVisitors(propertyId: string | undefined, date: string, status: string | undefined, pagination: Pagination) {
  const where = dayWhere(propertyId, date, status);
  const [rows, total] = await Promise.all([
    db.visitor.findMany({ where, include, orderBy: [{ inAt: 'desc' }, { expectedFrom: 'asc' }, { id: 'asc' }], skip: pagination.skip, take: pagination.limit }),
    db.visitor.count({ where }),
  ]);
  return paginated(await Promise.all(rows.map((r) => shape(r, true))), total, pagination);
}

/** The register as CSV for the day — what an inspector or the police ask for. */
/**
 * The whole day's register as CSV (Sprint L3); it stopped at the 300 the
 * screen showed. No photo links, so nothing is signed per row; the cap only
 * guards against a runaway day.
 */
export async function visitorsCsv(propertyId: string | undefined, date: string): Promise<string> {
  const found = await db.visitor.findMany({ where: dayWhere(propertyId, date), include, orderBy: [{ inAt: 'desc' }, { expectedFrom: 'asc' }, { id: 'asc' }], take: 20_000 });
  const rows = await Promise.all(found.map((r) => shape(r)));
  const esc = (v: unknown) => `"${String(v ?? '').replace(/"/g, '""')}"`;
  const head = ['Name', 'Phone', 'ID type', 'ID last 4', 'Visiting', 'Room', 'Purpose', 'Expected from', 'Expected to', 'In', 'Out', 'Status'];
  const lines = rows.map((r) => [r.name, r.phone, r.idType, r.idLast4, r.visiting?.name, r.visiting?.room, r.purpose, r.expectedFrom?.toISOString(), r.expectedTo?.toISOString(), r.inAt?.toISOString(), r.outAt?.toISOString(), r.status].map(esc).join(','));
  return [head.map(esc).join(','), ...lines].join('\n');
}

// ── Sprint 4 (TEPL): the visitor report ─────────────────────────────────────

const IST_MS = 330 * 60_000;

/**
 * Days from..to (India dates, at most 92): visitors per day (came in, left,
 * expected but never came), by purpose, the average stay, and the employees
 * with the most visitors.
 */
export async function visitorReport(propertyId: string | undefined, from: string, to: string) {
  const start = new Date(Date.parse(`${from}T00:00:00.000Z`) - IST_MS);
  const end = new Date(Date.parse(`${to}T00:00:00.000Z`) - IST_MS + 86_400_000);
  if (end <= start || end.getTime() - start.getTime() > 92 * 86_400_000) throw new BadRequestError('Up to three months at a time');
  const rows = await db.visitor.findMany({
    where: { ...(propertyId ? { propertyId } : {}), OR: [{ inAt: { gte: start, lt: end } }, { inAt: null, expectedFrom: { gte: start, lt: end } }] },
    select: { id: true, status: true, purpose: true, inAt: true, outAt: true, expectedFrom: true, preRegisteredBy: true, studentProfileId: true },
    take: 50000,
  });
  const dayOf = (d: Date) => new Date(d.getTime() + IST_MS).toISOString().slice(0, 10);
  const days = new Map<string, { day: string; visitors: number; left: number; stillIn: number; noShow: number; preRegistered: number }>();
  for (let t = start.getTime(); t < end.getTime(); t += 86_400_000) {
    const day = dayOf(new Date(t));
    days.set(day, { day, visitors: 0, left: 0, stillIn: 0, noShow: 0, preRegistered: 0 });
  }
  const purposes = new Map<string, number>();
  const visited = new Map<string, number>();
  const stays: number[] = [];
  for (const v of rows) {
    const when = v.inAt ?? v.expectedFrom;
    const d = when ? days.get(dayOf(when)) : undefined;
    if (!d) continue;
    if (!v.inAt) {
      if (v.status === 'NO_SHOW' || (v.expectedFrom && v.expectedFrom.getTime() < Date.now() - 86_400_000)) d.noShow++;
      continue;
    }
    d.visitors++;
    if (v.preRegisteredBy) d.preRegistered++;
    if (v.outAt) {
      d.left++;
      stays.push((v.outAt.getTime() - v.inAt.getTime()) / 60_000);
    } else d.stillIn++;
    const purpose = (v.purpose ?? '').trim().toLowerCase() || 'not given';
    purposes.set(purpose, (purposes.get(purpose) ?? 0) + 1);
    if (v.studentProfileId) visited.set(v.studentProfileId, (visited.get(v.studentProfileId) ?? 0) + 1);
  }
  const top = [...visited.entries()].sort((a, b) => b[1] - a[1]).slice(0, 15);
  const people = await db.studentProfile.findMany({
    where: { id: { in: top.map(([id]) => id) } },
    select: { id: true, employeeCode: true, user: { select: { name: true } }, bed: { select: { label: true, room: { select: { number: true } } } } },
  });
  const who = new Map(people.map((p) => [p.id, p]));
  const list = [...days.values()];
  return {
    from,
    to,
    totals: { visitors: list.reduce((n, d) => n + d.visitors, 0), noShow: list.reduce((n, d) => n + d.noShow, 0), preRegistered: list.reduce((n, d) => n + d.preRegistered, 0), avgStayMinutes: stays.length ? Math.round(stays.reduce((a, b) => a + b, 0) / stays.length) : null },
    days: list,
    byPurpose: [...purposes.entries()].map(([purpose, count]) => ({ purpose, count })).sort((a, b) => b.count - a.count),
    mostVisited: top.map(([id, visits]) => {
      const p = who.get(id);
      return { studentProfileId: id, name: p?.user.name ?? '—', employeeCode: p?.employeeCode ?? null, room: p?.bed ? `Room ${p.bed.room.number} · Bed ${p.bed.label}` : null, visits };
    }),
  };
}
