import { PassStatus, Prisma, Role, StudentRequestStatus, StudentRequestType } from '@prisma/client';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { importRoster, parseDay, type RosterRow } from '../roster/roster.service';
import { applyApprovalEffects } from '../leave/leave.service';
import { inBackground, notifyRequestUpdated } from '../notifications/notifications.service';

/**
 * TEPL's own systems (Sprint 6 connectors). Until their APIs are opened, the
 * plan's fallbacks stand: the roster file imported on screen, and leave
 * applied in the app. These take the same data from a machine:
 *
 * - Roster: rows of employee ID, date and shift code — the roster file's
 *   columns — pushed by their roster system (or the import screen).
 * - Plant leave: leave approved in the plant's HR system, each with that
 *   system's own reference. A new reference becomes an approved leave here
 *   (pass and meals off as usual); the same reference again updates it; a
 *   CANCELLED one cancels it. A daily file can carry the same rows.
 *
 * Every batch is kept as a run — what came, what was kept, what failed — so
 * the office can see the link is alive.
 */

const DAY_MS = 86_400_000;

async function recordRun(kind: 'ROSTER' | 'PLANT_LEAVE', source: 'FEED' | 'FILE', deviceId: string | null, received: number, accepted: number, errors: { row: number; message: string }[]) {
  return db.integrationRun.create({ data: { tenantId: getTenantIdOrThrow(), kind, source, deviceId, received, accepted, failed: errors.length, errors: errors.slice(0, 200) as Prisma.InputJsonValue } });
}

export async function rosterFeed(rows: RosterRow[], source: 'FEED' | 'FILE', deviceId: string | null) {
  const r = await importRoster(rows);
  await recordRun('ROSTER', source, deviceId, rows.length, r.saved, r.errors);
  return r;
}

export interface PlantLeaveRow {
  ref: string;
  employeeCode: string;
  leaveType: string;
  from: string;
  to: string;
  halfDay?: boolean;
  status?: 'APPROVED' | 'CANCELLED';
  note?: string | null;
}

/** The pass for a leave, if one was issued and is not yet used, is cancelled with it. */
async function undoLeave(requestId: string) {
  await db.gatePass.updateMany({ where: { requestId, status: { in: [PassStatus.ACTIVE, PassStatus.PENDING_GUARDIAN] } }, data: { status: PassStatus.CANCELLED } });
}

export async function plantLeaveFeed(rows: PlantLeaveRow[], source: 'FEED' | 'FILE', deviceId: string | null, actorId?: string) {
  const tenantId = getTenantIdOrThrow();
  // Passes need someone to have approved them: the person uploading, or the account's owner for a machine.
  const owner = actorId ?? (await db.user.findFirst({ where: { role: Role.HOSTEL_ADMIN }, orderBy: { createdAt: 'asc' }, select: { id: true } }))?.id;
  const [types, people] = await Promise.all([
    db.leaveType.findMany({ select: { id: true, code: true, name: true } }),
    db.studentProfile.findMany({ where: { employeeCode: { in: [...new Set(rows.map((r) => r.employeeCode.trim()))] } }, select: { id: true, employeeCode: true } }),
  ]);
  const typeOf = new Map(types.map((t) => [t.code.toLowerCase(), t]));
  const personOf = new Map(people.map((p) => [p.employeeCode!.toLowerCase(), p.id]));
  const errors: { row: number; message: string }[] = [];
  let created = 0;
  let updated = 0;
  let cancelled = 0;
  for (const [i, r] of rows.entries()) {
    const row = i + 2;
    const profileId = personOf.get(r.employeeCode.trim().toLowerCase());
    const type = typeOf.get(r.leaveType.trim().toLowerCase());
    const from = parseDay(r.from);
    const to = parseDay(r.to);
    if (!profileId) {
      errors.push({ row, message: `No employee with ID ${r.employeeCode}` });
      continue;
    }
    const existing = await db.studentRequest.findFirst({ where: { externalRef: r.ref } });
    if (r.status === 'CANCELLED') {
      if (!existing) {
        errors.push({ row, message: `Nothing to cancel for ${r.ref}` });
        continue;
      }
      if (existing.status !== StudentRequestStatus.CANCELLED) {
        await db.studentRequest.update({ where: { id: existing.id }, data: { status: StudentRequestStatus.CANCELLED, resolvedAt: new Date(), decisionNote: r.note ?? 'Cancelled at the plant' } });
        await undoLeave(existing.id);
        inBackground('push: leave cancelled', () => notifyRequestUpdated(tenantId, existing.id, { status: StudentRequestStatus.CANCELLED }));
        cancelled++;
      }
      continue;
    }
    if (!type) {
      errors.push({ row, message: `Leave type ${r.leaveType} is not in the leave policy` });
      continue;
    }
    if (!from || !to || to < from) {
      errors.push({ row, message: 'The dates are not valid' });
      continue;
    }
    const halfDay = !!r.halfDay && from.getTime() === to.getTime();
    const leaveDays = halfDay ? 0.5 : Math.round((to.getTime() - from.getTime()) / DAY_MS) + 1;
    if (existing) {
      // Same leave again: the dates may have moved.
      if (existing.fromDate?.getTime() !== from.getTime() || existing.toDate?.getTime() !== to.getTime() || existing.leaveTypeId !== type.id) {
        await db.studentRequest.update({ where: { id: existing.id }, data: { fromDate: from, toDate: to, leaveTypeId: type.id, leaveDays, halfDay } });
        updated++;
      }
      continue;
    }
    const clash = await db.studentRequest.findFirst({ where: { studentProfileId: profileId, type: StudentRequestType.LEAVE, status: { in: [StudentRequestStatus.OPEN, StudentRequestStatus.IN_PROGRESS, StudentRequestStatus.APPROVED] }, fromDate: { lte: to }, toDate: { gte: from } }, select: { id: true } });
    if (clash) {
      errors.push({ row, message: `Overlaps a leave already here for ${r.employeeCode}` });
      continue;
    }
    const now = new Date();
    const req = await db.studentRequest.create({
      data: { tenantId, studentProfileId: profileId, type: StudentRequestType.LEAVE, subject: `${type.name} (approved at the plant)`, body: r.note || 'Approved in the plant HR system.', fromDate: from, toDate: to, leaveTypeId: type.id, leaveDays, halfDay, leaveStage: 'DONE', status: StudentRequestStatus.APPROVED, plantApprovedAt: now, resolvedAt: now, externalRef: r.ref },
    });
    if (owner) await applyApprovalEffects(req.id, owner);
    inBackground('push: plant leave', () => notifyRequestUpdated(tenantId, req.id, { status: StudentRequestStatus.APPROVED }));
    created++;
  }
  await recordRun('PLANT_LEAVE', source, deviceId, rows.length, created + updated + cancelled, errors);
  return { received: rows.length, created, updated, cancelled, failed: errors.length, errors };
}

export async function runs(kind?: 'ROSTER' | 'PLANT_LEAVE') {
  const rows = await db.integrationRun.findMany({ where: kind ? { kind } : {}, orderBy: { at: 'desc' }, take: 50 });
  const last = async (k: string) => db.integrationRun.findFirst({ where: { kind: k }, orderBy: { at: 'desc' }, select: { at: true, source: true, received: true, accepted: true, failed: true } });
  return { runs: rows, lastRoster: await last('ROSTER'), lastPlantLeave: await last('PLANT_LEAVE') };
}
