import { Role } from '@prisma/client';
import { db, prismaUnscoped } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';
import { effectivePermissions } from '../../lib/permissions';
import { tenantHasFeature } from '../../middleware/requireFeature';
import { pushTo } from '../notifications/notifications.service';

/**
 * The bus log (Sprint 4, TEPL): the buses and vans that take employees to
 * the plant, and each trip as the gate sees it — out with how many and when
 * it should be back, then in. A trip not back half an hour after it was due
 * is flagged once and the gate hears of it.
 */

const IST_MS = 330 * 60_000;
const DAY = 86_400_000;
const LATE_MS = 30 * 60_000;

// ── Vehicles ────────────────────────────────────────────────────────────────

export interface VehicleInput {
  number: string;
  kind?: string;
  capacity?: number | null;
  operator?: string | null;
  driverName?: string | null;
  driverPhone?: string | null;
  propertyId?: string | null;
  isActive?: boolean;
}

const plate = (n: string) => n.toUpperCase().replace(/\s+/g, ' ').trim();

export function listVehicles(includeInactive = false) {
  return db.vehicle.findMany({ where: includeInactive ? {} : { isActive: true }, orderBy: [{ isActive: 'desc' }, { number: 'asc' }], take: 500 });
}

export async function createVehicle(input: VehicleInput) {
  const number = plate(input.number);
  if (await db.vehicle.findFirst({ where: { number }, select: { id: true } })) throw new ConflictError(`${number} is already on the list`);
  return db.vehicle.create({ data: { ...input, number, tenantId: getTenantIdOrThrow() } });
}

export async function updateVehicle(id: string, input: Partial<VehicleInput>) {
  const v = await db.vehicle.findFirst({ where: { id } });
  if (!v) throw new NotFoundError('Vehicle not found');
  const number = input.number !== undefined ? plate(input.number) : undefined;
  if (number && number !== v.number && (await db.vehicle.findFirst({ where: { number }, select: { id: true } }))) throw new ConflictError(`${number} is already on the list`);
  return db.vehicle.update({ where: { id }, data: { ...input, ...(number ? { number } : {}) } });
}

// ── Trips ───────────────────────────────────────────────────────────────────

const tripInclude = { vehicle: { select: { id: true, number: true, kind: true, capacity: true, driverName: true } } } as const;

async function activeVehicle(id: string) {
  const v = await db.vehicle.findFirst({ where: { id, isActive: true } });
  if (!v) throw new NotFoundError('Vehicle not found');
  return v;
}

const openTrip = (vehicleId: string) => db.busTrip.findFirst({ where: { vehicleId, departedAt: { not: null }, arrivedAt: null }, orderBy: { departedAt: 'desc' } });

function checkPassengers(n: number | null | undefined, capacity: number | null) {
  if (n !== null && n !== undefined && capacity && n > capacity * 1.5) throw new BadRequestError(`That is far over the vehicle's ${capacity} seats — check the count`);
}

/** The bus leaves the campus. */
export async function depart(input: { vehicleId: string; passengers?: number | null; route?: string | null; expectedReturnAt?: Date | null; driverName?: string | null; note?: string | null }, actorId: string, propertyId?: string) {
  const v = await activeVehicle(input.vehicleId);
  if (await openTrip(v.id)) throw new ConflictError(`${v.number} is already out — log its return first`);
  checkPassengers(input.passengers, v.capacity);
  const now = new Date();
  if (input.expectedReturnAt && input.expectedReturnAt <= now) throw new BadRequestError('The expected return must be later than now');
  return db.busTrip.create({
    data: { tenantId: getTenantIdOrThrow(), propertyId: propertyId ?? v.propertyId, vehicleId: v.id, route: input.route ?? null, departedAt: now, passengersOut: input.passengers ?? null, expectedReturnAt: input.expectedReturnAt ?? null, driverName: input.driverName ?? v.driverName, note: input.note ?? null, loggedOutById: actorId },
    include: tripInclude,
  });
}

/** The bus comes in: closes its trip out, or is an arrival on its own (dropping a shift back). */
export async function arrive(input: { vehicleId: string; passengers?: number | null; route?: string | null; driverName?: string | null; note?: string | null }, actorId: string, propertyId?: string) {
  // A vehicle taken off the list while out can still be logged back in.
  const v = await db.vehicle.findFirst({ where: { id: input.vehicleId } });
  if (!v) throw new NotFoundError('Vehicle not found');
  checkPassengers(input.passengers, v.capacity);
  const open = await openTrip(v.id);
  if (!open && !v.isActive) throw new NotFoundError('Vehicle not found');
  const now = new Date();
  if (open) {
    return db.busTrip.update({ where: { id: open.id }, data: { arrivedAt: now, passengersIn: input.passengers ?? null, loggedInById: actorId, ...(input.note ? { note: [open.note, input.note].filter(Boolean).join(' · ') } : {}) }, include: tripInclude });
  }
  return db.busTrip.create({
    data: { tenantId: getTenantIdOrThrow(), propertyId: propertyId ?? v.propertyId, vehicleId: v.id, route: input.route ?? null, arrivedAt: now, passengersIn: input.passengers ?? null, driverName: input.driverName ?? v.driverName, note: input.note ?? null, loggedInById: actorId },
    include: tripInclude,
  });
}

/** The office corrects a trip: counts, route, times. */
export async function updateTrip(id: string, input: { passengersOut?: number | null; passengersIn?: number | null; route?: string | null; expectedReturnAt?: Date | null; departedAt?: Date | null; arrivedAt?: Date | null; note?: string | null }) {
  const t = await db.busTrip.findFirst({ where: { id } });
  if (!t) throw new NotFoundError('Trip not found');
  const departedAt = input.departedAt !== undefined ? input.departedAt : t.departedAt;
  const arrivedAt = input.arrivedAt !== undefined ? input.arrivedAt : t.arrivedAt;
  if (departedAt && arrivedAt && arrivedAt < departedAt) throw new BadRequestError('It cannot be back before it left');
  // Reopening a trip: only if the vehicle is not already out on another.
  if (departedAt && !arrivedAt && t.arrivedAt) {
    const other = await db.busTrip.findFirst({ where: { vehicleId: t.vehicleId, id: { not: id }, departedAt: { not: null }, arrivedAt: null }, select: { id: true } });
    if (other) throw new ConflictError('This vehicle is already out on another trip');
  }
  return db.busTrip.update({ where: { id }, data: input, include: tripInclude });
}

const dayBounds = (ymd: string) => {
  const start = new Date(Date.parse(`${ymd}T00:00:00.000Z`) - IST_MS);
  return { start, end: new Date(start.getTime() + DAY) };
};
const minutesBetween = (a: Date | null, b: Date | null) => (a && b ? Math.round((b.getTime() - a.getTime()) / 60_000) : null);

/** The gate's day: buses out now (late ones first), and every trip that moved today. */
export async function dayBoard(ymd: string, propertyId?: string) {
  const { start, end } = dayBounds(ymd);
  const scope = propertyId ? { propertyId } : {};
  const [out, trips] = await Promise.all([
    // Out now is every block's: a bus out from the other block is not here either.
    db.busTrip.findMany({ where: { departedAt: { not: null }, arrivedAt: null }, include: tripInclude, orderBy: { expectedReturnAt: 'asc' } }),
    db.busTrip.findMany({ where: { ...scope, OR: [{ departedAt: { gte: start, lt: end } }, { arrivedAt: { gte: start, lt: end } }] }, include: tripInclude, orderBy: { createdAt: 'desc' }, take: 500 }),
  ]);
  const now = Date.now();
  const late = (t: { expectedReturnAt: Date | null; arrivedAt: Date | null }) => !!t.expectedReturnAt && (t.arrivedAt ? t.arrivedAt.getTime() : now) > t.expectedReturnAt.getTime() + LATE_MS;
  const shape = <T extends { expectedReturnAt: Date | null; arrivedAt: Date | null; departedAt: Date | null }>(t: T) => ({ ...t, late: late(t), minutesOut: minutesBetween(t.departedAt, t.arrivedAt) });
  return {
    day: ymd,
    out: out.map(shape),
    trips: trips.map(shape),
    summary: {
      trips: trips.length,
      out: out.length,
      late: out.filter(late).length,
      passengersOut: trips.reduce((n, t) => n + (t.passengersOut ?? 0), 0),
      passengersIn: trips.reduce((n, t) => n + (t.passengersIn ?? 0), 0),
    },
  };
}

/** Days from..to (India dates, at most 92): per vehicle, trips, passengers, average time out and late returns. */
export async function tripReport(from: string, to: string, propertyId?: string) {
  const a = dayBounds(from).start;
  const b = dayBounds(to).end;
  if (b <= a || b.getTime() - a.getTime() > 92 * DAY) throw new BadRequestError('Up to three months at a time');
  const trips = await db.busTrip.findMany({ where: { ...(propertyId ? { propertyId } : {}), OR: [{ departedAt: { gte: a, lt: b } }, { arrivedAt: { gte: a, lt: b }, departedAt: null }] }, include: tripInclude, take: 20000 });
  const byVehicle = new Map<string, { vehicleId: string; number: string; trips: number; passengersOut: number; passengersIn: number; minutes: number[]; late: number }>();
  const byDay = new Map<string, { day: string; trips: number; passengers: number; late: number }>();
  for (const t of trips) {
    const v = byVehicle.get(t.vehicleId) ?? { vehicleId: t.vehicleId, number: t.vehicle.number, trips: 0, passengersOut: 0, passengersIn: 0, minutes: [], late: 0 };
    const isLate = !!t.expectedReturnAt && !!t.arrivedAt && t.arrivedAt.getTime() > t.expectedReturnAt.getTime() + LATE_MS;
    v.trips++;
    v.passengersOut += t.passengersOut ?? 0;
    v.passengersIn += t.passengersIn ?? 0;
    const m = minutesBetween(t.departedAt, t.arrivedAt);
    if (m !== null) v.minutes.push(m);
    if (isLate) v.late++;
    byVehicle.set(t.vehicleId, v);
    const day = new Date((t.departedAt ?? t.arrivedAt)!.getTime() + IST_MS).toISOString().slice(0, 10);
    const d = byDay.get(day) ?? { day, trips: 0, passengers: 0, late: 0 };
    d.trips++;
    d.passengers += (t.passengersOut ?? 0) + (t.passengersIn ?? 0);
    if (isLate) d.late++;
    byDay.set(day, d);
  }
  return {
    from,
    to,
    vehicles: [...byVehicle.values()].map(({ minutes, ...v }) => ({ ...v, avgMinutesOut: minutes.length ? Math.round(minutes.reduce((x, y) => x + y, 0) / minutes.length) : null })).sort((x, y) => y.trips - x.trips),
    days: [...byDay.values()].sort((x, y) => x.day.localeCompare(y.day)),
    trips,
  };
}

/** Hourly: a bus out more than half an hour past its expected return is flagged once; the gate hears of it. */
export async function runBusOverduePass(now = new Date()) {
  const late = await prismaUnscoped.busTrip.findMany({
    where: { arrivedAt: null, departedAt: { not: null }, overdueFlaggedAt: null, expectedReturnAt: { lt: new Date(now.getTime() - LATE_MS) } },
    include: { vehicle: { select: { number: true } } },
    take: 200,
  });
  for (const t of late) {
    if (!(await tenantHasFeature(t.tenantId, 'busLog'))) continue;
    await prismaUnscoped.busTrip.update({ where: { id: t.id }, data: { overdueFlaggedAt: now } });
    const staff = await prismaUnscoped.user.findMany({ where: { tenantId: t.tenantId, role: { in: [Role.HOSTEL_ADMIN, Role.WARDEN, Role.GUARD] }, deactivatedAt: null }, select: { id: true, role: true, customRole: { select: { permissions: true } } } });
    const to = staff.filter((u) => effectivePermissions(u.role, u.customRole?.permissions).includes('MANAGE_GATE')).map((u) => u.id);
    await pushTo(t.tenantId, 'BUS_OVERDUE', t.id, to, {
      title: `${t.vehicle.number} is not back`,
      body: `Due back ${t.expectedReturnAt!.toLocaleTimeString('en-IN', { hour: 'numeric', minute: '2-digit', timeZone: 'Asia/Kolkata' })}${t.route ? ` from ${t.route}` : ''}.`,
      data: { tripId: t.id },
    }).catch((err) => console.error('[push] bus overdue failed:', err)); // eslint-disable-line no-console
  }
}
