import { DevicePurpose, PunchType } from '@prisma/client';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { monthRange } from '../../lib/period';
import { paginated, type Pagination } from '../../lib/pagination';
import { checkInOnArrival } from '../students/employee-record';
import { assignBed } from '../students/students.service';
import { inBackground, notifyArrivalCheckIn } from '../notifications/notifications.service';
import { ingestStaffPunches } from '../staff-attendance/staff-attendance.service';
import { applyGateSwipes } from '../outings/outings.service';
import { mealClassifier } from '../canteen/canteen.service';
import { tenantHasFeature } from '../../middleware/requireFeature';

/** A device's configured purpose decides the punch type when it doesn't send one. */
const DEFAULT_TYPE: Record<Exclude<DevicePurpose, 'BMS' | 'ASSET_TAGS' | 'HR_FEED' | 'LAUNDRY'>, PunchType> = {
  GATE: PunchType.GATE_IN, // refined below by alternating in/out
  MESS: PunchType.MESS,
  ROLLCALL: PunchType.ROLLCALL,
};

export interface IncomingPunch {
  biometricId: string;
  punchedAt: string;
  type?: PunchType;
}

/**
 * Ingest a batch of punches from one terminal.
 *
 * Idempotent: terminals re-send batches after a network drop, so a punch is
 * keyed by (device, biometricId, punchedAt) and duplicates are skipped rather
 * than double-counted.
 *
 * Unknown biometric ids are still stored (with no student link) so an admin can
 * see unrecognised punches instead of silently losing them.
 */
export async function ingestPunches(
  device: { id: string; tenantId: string; purpose: DevicePurpose },
  punches: IncomingPunch[],
) {
  // Map enrolled biometric ids → students, in one query.
  const ids = [...new Set(punches.map((p) => p.biometricId))];
  // Sprint 1 (TEPL): a terminal reading ID cards reports the card number, so
  // that matches too. Only employee records carry one; nothing else changes.
  const students = await db.studentProfile.findMany({
    where: { OR: [{ biometricId: { in: ids } }, { cardNumber: { in: ids } }] },
    select: { id: true, biometricId: true, cardNumber: true, arrivalBedId: true, bedId: true, propertyId: true },
  });
  const byBiometricId = new Map<string, string>();
  for (const s of students) if (s.cardNumber) byBiometricId.set(s.cardNumber, s.id);
  for (const s of students) if (s.biometricId) byBiometricId.set(s.biometricId, s.id);
  // Sprint 5 (TEPL): a mess punch is tagged with its meal, by the block's meal windows.
  const classify = (await tenantHasFeature(device.tenantId, 'canteen')) ? mealClassifier(device.tenantId) : null;
  const propertyOf = new Map(students.map((s) => [s.id, s.propertyId]));
  // Employees waiting to arrive: their first punch here moves them into the bed held for them.
  const arriving = new Map(students.filter((s) => s.arrivalBedId && !s.bedId).map((s) => [s.id, null as Date | null]));

  let accepted = 0;
  let duplicates = 0;
  let unmatched = 0;
  // Sprint 3 (TEPL): ids that are no resident's may be staff clocking in.
  const forStaff: { biometricId: string; at: Date }[] = [];
  const messDays: { studentProfileId: string; date: Date }[] = [];
  // Sprint 4 (TEPL): gate swipes move an employee's pass along.
  const gateSwipes: { studentProfileId: string; type: PunchType; at: Date }[] = [];

  for (const p of punches) {
    const punchedAt = new Date(p.punchedAt);
    if (Number.isNaN(punchedAt.getTime())) continue;

    const studentProfileId = byBiometricId.get(p.biometricId) ?? null;
    if (!studentProfileId) {
      unmatched++;
      forStaff.push({ biometricId: p.biometricId, at: punchedAt });
    }

    const type = p.type ?? (device.purpose === DevicePurpose.GATE
      ? await nextGateDirection(studentProfileId)
      : DEFAULT_TYPE[device.purpose === 'BMS' || device.purpose === 'ASSET_TAGS' || device.purpose === 'HR_FEED' || device.purpose === 'LAUNDRY' ? 'ROLLCALL' : device.purpose]);

    try {
      await db.biometricPunch.create({
        data: {
          tenantId: device.tenantId,
          deviceId: device.id,
          biometricId: p.biometricId,
          studentProfileId,
          type,
          punchedAt,
          ...(type === PunchType.MESS && classify ? { meal: await classify(studentProfileId ? propertyOf.get(studentProfileId) : null, punchedAt) } : {}),
        },
      });
      accepted++;
      if (studentProfileId && arriving.has(studentProfileId)) {
        const first = arriving.get(studentProfileId);
        if (!first || punchedAt < first) arriving.set(studentProfileId, punchedAt);
      }
      if (studentProfileId && (type === PunchType.GATE_IN || type === PunchType.GATE_OUT)) gateSwipes.push({ studentProfileId, type, at: punchedAt });
      if (type === PunchType.MESS && studentProfileId) {
        messDays.push({ studentProfileId, date: startOfDayUtc(punchedAt) });
      }
    } catch (err) {
      // Unique violation = the same punch already ingested.
      if ((err as { code?: string }).code === 'P2002') duplicates++;
      else throw err;
    }
  }

  // A mess punch is proof the student actually ate — record attendance so
  // billing reflects reality (and clears any stale opt-out for that day).
  for (const { studentProfileId, date } of messDays) {
    const existing = await db.messAttendance.findFirst({ where: { studentProfileId, date } });
    if (existing) {
      if (!existing.present) await db.messAttendance.update({ where: { id: existing.id }, data: { present: true } });
    } else {
      await db.messAttendance.create({ data: { tenantId: device.tenantId, studentProfileId, date, present: true } });
    }
  }

  const staffPunches = await ingestStaffPunches(device.tenantId, device.id, forStaff);
  const passesMoved = await applyGateSwipes(device.tenantId, gateSwipes);
  let checkedIn = 0;
  for (const [studentProfileId, at] of arriving) {
    if (!at) continue;
    const moved = await checkInOnArrival(studentProfileId, at, assignBed).catch((err) => {
      console.error('[biometric] arrival check-in failed:', err); // eslint-disable-line no-console
      return null;
    });
    if (moved) {
      checkedIn++;
      inBackground('push: arrival check-in', () => notifyArrivalCheckIn(device.tenantId, studentProfileId, moved));
    }
  }

  await db.biometricDevice.update({ where: { id: device.id }, data: { lastSeenAt: new Date() } });
  return { received: punches.length, accepted, duplicates, unmatched, ...(checkedIn ? { checkedIn } : {}), ...(staffPunches ? { staffPunches } : {}), ...(passesMoved ? { passesMoved } : {}) };
}

/** Gate terminals usually report a single "punch"; alternate IN/OUT per person. */
async function nextGateDirection(studentProfileId: string | null): Promise<PunchType> {
  if (!studentProfileId) return PunchType.GATE_IN;
  const last = await db.biometricPunch.findFirst({
    where: { studentProfileId, type: { in: [PunchType.GATE_IN, PunchType.GATE_OUT] } },
    orderBy: { punchedAt: 'desc' },
    select: { type: true },
  });
  return last?.type === PunchType.GATE_IN ? PunchType.GATE_OUT : PunchType.GATE_IN;
}

function startOfDayUtc(d: Date): Date {
  return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
}

// ── Read models ────────────────────────────────────────────────────────────

/**
 * Counts for the biometric stat cards. Presence is already a summary, so only
 * the device count needs its own query.
 */
export async function deviceStats(propertyId?: string) {
  const where = propertyId
    ? { OR: [{ propertyId }, { propertyId: null }] }
    : {};
  return { devices: await db.biometricDevice.count({ where }) };
}

export async function listPunches(
  filters: { limit?: number; type?: PunchType; propertyId?: string },
  pagination?: Pagination | null,
) {
  const where = {
    ...(filters.type ? { type: filters.type } : {}),
    // Filter to the active property, but never hide punches from unenrolled
    // biometric ids — surfacing those is the whole point of storing them.
    ...(filters.propertyId
      ? { OR: [{ student: { propertyId: filters.propertyId } }, { studentProfileId: null }] }
      : {}),
  };
  const include = {
    student: { include: { user: { select: { name: true } } } },
    device: { select: { name: true, purpose: true } },
  };
  const orderBy = { punchedAt: 'desc' as const };

  // The legacy `limit` stays honoured for callers that have not moved to pages.
  if (!pagination) {
    return db.biometricPunch.findMany({
      where,
      include,
      orderBy,
      take: Math.min(filters.limit ?? 50, 200),
    });
  }

  const [items, total] = await Promise.all([
    db.biometricPunch.findMany({
      where,
      include,
      orderBy,
      skip: pagination.skip,
      take: pagination.limit,
    }),
    db.biometricPunch.count({ where }),
  ]);
  return paginated(items, total, pagination);
}

/** Current in/out status per student, from their latest gate punch. */
export async function getPresence(propertyId?: string) {
  const students = await db.studentProfile.findMany({
    where: { ...(propertyId ? { propertyId } : {}), biometricId: { not: null } },
    include: {
      user: { select: { name: true } },
      punches: {
        where: { type: { in: [PunchType.GATE_IN, PunchType.GATE_OUT] } },
        orderBy: { punchedAt: 'desc' },
        take: 1,
      },
    },
    orderBy: { createdAt: 'asc' },
  });

  const rows = students.map((s) => {
    const last = s.punches[0];
    return {
      studentProfileId: s.id,
      name: s.user.name,
      status: last?.type === PunchType.GATE_IN ? ('IN' as const) : last ? ('OUT' as const) : ('UNKNOWN' as const),
      lastSeenAt: last?.punchedAt ?? null,
    };
  });

  return {
    summary: {
      in: rows.filter((r) => r.status === 'IN').length,
      out: rows.filter((r) => r.status === 'OUT').length,
      unknown: rows.filter((r) => r.status === 'UNKNOWN').length,
    },
    students: rows,
  };
}

/** Daily roll-call register for a month: which days each student was recorded. */
export async function getRollcall(period: string, propertyId?: string) {
  const { start, end } = monthRange(period);
  const punches = await db.biometricPunch.findMany({
    where: {
      punchedAt: { gte: start, lte: end },
      type: { in: [PunchType.ROLLCALL, PunchType.GATE_IN] },
      studentProfileId: { not: null },
      ...(propertyId ? { student: { propertyId } } : {}),
    },
    include: { student: { include: { user: { select: { name: true } } } } },
  });

  const byStudent = new Map<string, { name: string; days: Set<string> }>();
  for (const p of punches) {
    const key = p.studentProfileId!;
    const entry = byStudent.get(key) ?? { name: p.student!.user.name, days: new Set<string>() };
    entry.days.add(p.punchedAt.toISOString().slice(0, 10));
    byStudent.set(key, entry);
  }

  return {
    period,
    students: [...byStudent.entries()].map(([studentProfileId, v]) => ({
      studentProfileId,
      name: v.name,
      daysPresent: v.days.size,
      dates: [...v.days].sort(),
    })),
  };
}

export function currentTenantId(): string {
  return getTenantIdOrThrow();
}
