import { Prisma, Role, type LostFoundItem } from '@prisma/client';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { BadRequestError, ConflictError, ForbiddenError, NotFoundError } from '../../lib/errors';
import type { Permission } from '../../lib/permissions';
import { inBackground, notifyLostFound, notifyParcelArrived } from '../notifications/notifications.service';
import { paginated, type Pagination } from '../../lib/pagination';

/**
 * The front desk (Sprint 2, TEPL): parcels at the gate, the emergency
 * directory, and lost and found. The desk is security (MANAGE_GATE) and the
 * hostel office (MANAGE_STUDENTS); employees see their own parcels, the
 * directory, and found items they might claim.
 */

export const isDesk = (perms: Permission[]) => perms.includes('MANAGE_GATE') || perms.includes('MANAGE_STUDENTS');
export function assertDesk(perms: Permission[]) {
  if (!isDesk(perms)) throw new ForbiddenError('Requires permission: MANAGE_GATE or MANAGE_STUDENTS');
}

async function profileOf(userId: string) {
  const p = await db.studentProfile.findFirst({ where: { userId }, select: { id: true, propertyId: true } });
  if (!p) throw new NotFoundError('No employee record for this account');
  return p;
}

const IST_MS = 330 * 60_000;

// ── Parcels ─────────────────────────────────────────────────────────────────

const parcelInclude = {
  student: { select: { id: true, employeeCode: true, user: { select: { name: true, phone: true } }, bed: { select: { label: true, room: { select: { number: true } } } } } },
} as const;

export async function logParcel(input: { studentProfileId: string; courier?: string | null; trackingNo?: string | null; description?: string | null; note?: string | null }, actorId: string) {
  const profile = await db.studentProfile.findFirst({ where: { id: input.studentProfileId }, select: { id: true, propertyId: true } });
  if (!profile) throw new NotFoundError('Employee not found');
  const tenantId = getTenantIdOrThrow();
  const parcel = await db.parcel.create({ data: { tenantId, ...input, propertyId: profile.propertyId, receivedById: actorId }, include: parcelInclude });
  inBackground('push: parcel arrived', () => notifyParcelArrived(tenantId, parcel.id));
  return parcel;
}

function parcelWhere(f: { status?: string; q?: string; propertyId?: string }): Prisma.ParcelWhereInput {
  return {
    ...(f.status ? { status: f.status } : {}),
    ...(f.propertyId ? { propertyId: f.propertyId } : {}),
    ...(f.q
      ? {
          OR: [
            { trackingNo: { contains: f.q, mode: 'insensitive' } },
            { courier: { contains: f.q, mode: 'insensitive' } },
            { student: { user: { name: { contains: f.q, mode: 'insensitive' } } } },
            { student: { employeeCode: { contains: f.q, mode: 'insensitive' } } },
          ],
        }
      : {}),
  };
}

export async function listParcels(f: { status?: string; q?: string; propertyId?: string }) {
  return db.parcel.findMany({ where: parcelWhere(f), include: parcelInclude, orderBy: [{ status: 'desc' }, { receivedAt: 'desc' }], take: 300 });
}

/**
 * The parcel log a page at a time (Sprint L3), waiting first and newest first
 * as before, so a busy gate's older parcels stay reachable. The id breaks ties.
 */
export async function pageParcels(f: { status?: string; q?: string; propertyId?: string }, pagination: Pagination) {
  const where = parcelWhere(f);
  const [rows, total] = await Promise.all([
    db.parcel.findMany({ where, include: parcelInclude, orderBy: [{ status: 'desc' }, { receivedAt: 'desc' }, { id: 'asc' }], skip: pagination.skip, take: pagination.limit }),
    db.parcel.count({ where }),
  ]);
  return paginated(rows, total, pagination);
}

/** Handed to the employee, or sent back to the courier. */
export async function closeParcel(id: string, to: 'COLLECTED' | 'RETURNED', actorId: string, note?: string) {
  const p = await db.parcel.findFirst({ where: { id } });
  if (!p) throw new NotFoundError('Parcel not found');
  if (p.status !== 'WAITING') throw new ConflictError('This parcel has already left the gate');
  return db.parcel.update({ where: { id }, data: { status: to, collectedAt: new Date(), handedOverById: actorId, ...(note ? { note } : {}) }, include: parcelInclude });
}

export async function parcelCounts(propertyId?: string) {
  return { waiting: await db.parcel.count({ where: { status: 'WAITING', ...(propertyId ? { propertyId } : {}) } }) };
}

export async function myParcels(userId: string) {
  const p = await profileOf(userId);
  return db.parcel.findMany({
    where: { studentProfileId: p.id, OR: [{ status: 'WAITING' }, { collectedAt: { gte: new Date(Date.now() - 30 * 86_400_000) } }] },
    orderBy: [{ status: 'desc' }, { receivedAt: 'desc' }],
    take: 50,
    select: { id: true, courier: true, trackingNo: true, description: true, status: true, receivedAt: true, collectedAt: true, note: true },
  });
}

// ── Emergency contacts ──────────────────────────────────────────────────────

/** The block an employee lives in, for their directory. */
export async function employeeProperty(userId: string) {
  return (await db.studentProfile.findFirst({ where: { userId }, select: { propertyId: true } }))?.propertyId ?? null;
}

export const CONTACT_ROLES = ['WARDEN', 'OHC', 'SECURITY', 'MAINTENANCE', 'DOCTOR', 'AMBULANCE', 'FIRE', 'POLICE', 'HR', 'OTHER'] as const;

const minutes = (hhmm: string) => {
  const [h, m] = hhmm.split(':').map(Number);
  return h * 60 + m;
};

/** On duty at this India-time minute of the day: no hours = always; an end before the start runs past midnight. */
export function onDuty(c: { startTime: string | null; endTime: string | null }, now = new Date()) {
  if (!c.startTime || !c.endTime) return true;
  const ist = new Date(now.getTime() + IST_MS);
  const t = ist.getUTCHours() * 60 + ist.getUTCMinutes();
  const s = minutes(c.startTime);
  const e = minutes(c.endTime);
  return s <= e ? t >= s && t < e : t >= s || t < e;
}

/** The directory for a property: its own contacts and the tenant-wide ones; who is on duty now first. */
export async function listContacts(propertyId: string | undefined, includeInactive = false) {
  const rows = await db.emergencyContact.findMany({
    where: { ...(includeInactive ? {} : { isActive: true }), ...(propertyId ? { OR: [{ propertyId }, { propertyId: null }] } : {}) },
    orderBy: [{ sortOrder: 'asc' }, { name: 'asc' }],
    take: 200,
  });
  const now = new Date();
  return rows.map((c) => ({ ...c, onDutyNow: onDuty(c, now) })).sort((a, b) => Number(b.onDutyNow) - Number(a.onDutyNow));
}

export interface ContactInput {
  name: string;
  role: string;
  phone: string;
  altPhone?: string | null;
  startTime?: string | null;
  endTime?: string | null;
  external?: boolean;
  note?: string | null;
  propertyId?: string | null;
  sortOrder?: number;
  isActive?: boolean;
}

function checkHours(c: { startTime?: string | null; endTime?: string | null }) {
  if (!!c.startTime !== !!c.endTime) throw new BadRequestError('Give both the start and the end of their hours, or neither');
}

export async function createContact(input: ContactInput) {
  checkHours(input);
  if (input.propertyId && !(await db.property.findFirst({ where: { id: input.propertyId }, select: { id: true } }))) throw new NotFoundError('Property not found');
  return db.emergencyContact.create({ data: { ...input, tenantId: getTenantIdOrThrow() } });
}

export async function updateContact(id: string, input: Partial<ContactInput>) {
  const c = await db.emergencyContact.findFirst({ where: { id } });
  if (!c) throw new NotFoundError('Contact not found');
  checkHours({ startTime: input.startTime !== undefined ? input.startTime : c.startTime, endTime: input.endTime !== undefined ? input.endTime : c.endTime });
  return db.emergencyContact.update({ where: { id }, data: input });
}

export async function deleteContact(id: string) {
  const c = await db.emergencyContact.findFirst({ where: { id } });
  if (!c) throw new NotFoundError('Contact not found');
  await db.emergencyContact.delete({ where: { id } });
  return { ok: true };
}

// ── Lost and found ──────────────────────────────────────────────────────────

export const LOST_CATEGORIES = ['PHONE', 'WALLET', 'KEYS', 'ID_CARD', 'BAG', 'CLOTHING', 'ELECTRONICS', 'DOCUMENTS', 'OTHER'] as const;

export interface ItemInput {
  title: string;
  description?: string | null;
  category?: string | null;
  location?: string | null;
  happenedAt: Date;
}

/** The desk logs a found item. Anyone who reported losing something of the same kind in the last month hears of it. */
export async function logFound(input: ItemInput, actorId: string, propertyId?: string) {
  const tenantId = getTenantIdOrThrow();
  const item = await db.lostFoundItem.create({ data: { tenantId, kind: 'FOUND', ...input, propertyId: propertyId ?? null, reportedById: actorId } });
  if (input.category) {
    const lost = await db.lostFoundItem.findMany({
      where: { kind: 'LOST', status: 'OPEN', category: input.category, happenedAt: { gte: new Date(Date.now() - 30 * 86_400_000) }, reporterProfileId: { not: null } },
      select: { reporterProfileId: true },
      take: 50,
    });
    const users = (await db.studentProfile.findMany({ where: { id: { in: lost.map((l) => l.reporterProfileId!) } }, select: { userId: true } })).map((p) => p.userId);
    if (users.length) inBackground('push: lost and found match', () => notifyLostFound(tenantId, item.id, 'MATCH', users));
  }
  return item;
}

/** An employee tells the desk what they lost. */
export async function reportLost(userId: string, input: ItemInput) {
  const p = await profileOf(userId);
  return db.lostFoundItem.create({ data: { tenantId: getTenantIdOrThrow(), kind: 'LOST', ...input, propertyId: p.propertyId, reportedById: userId, reporterProfileId: p.id } });
}

/**
 * The register, or with `pagination` one page of it and the total (Sprint L3);
 * the order, the filters and what each viewer may see are the same either way.
 */
export async function listItems(viewer: { userId: string; role: Role; perms: Permission[] }, f: { kind?: 'FOUND' | 'LOST'; status?: string; category?: string; mine?: boolean; q?: string; propertyId?: string; matches?: boolean }, pagination?: Pagination | null) {
  const where: Prisma.LostFoundItemWhereInput = {
    ...(f.kind ? { kind: f.kind } : {}),
    ...(f.status ? { status: f.status } : {}),
    ...(f.category ? { category: f.category } : {}),
    ...(f.propertyId ? { OR: [{ propertyId: f.propertyId }, { propertyId: null }] } : {}),
    ...(f.q ? { AND: [{ OR: [{ title: { contains: f.q, mode: 'insensitive' } }, { description: { contains: f.q, mode: 'insensitive' } }, { location: { contains: f.q, mode: 'insensitive' } }] }] } : {}),
  };
  if (viewer.role === Role.STUDENT) {
    // An employee sees found items still waiting for an owner, and their own reports and claims.
    const p = await profileOf(viewer.userId);
    const own: Prisma.LostFoundItemWhereInput[] = [{ reporterProfileId: p.id }, { claimantProfileId: p.id }];
    const scoped: Prisma.LostFoundItemWhereInput = { AND: [where, { OR: f.mine ? own : [{ kind: 'FOUND', status: 'OPEN' }, ...own] }] };
    const [rows, total] = await Promise.all([
      db.lostFoundItem.findMany({
        where: scoped,
        orderBy: pagination ? [{ happenedAt: 'desc' }, { id: 'asc' }] : { happenedAt: 'desc' },
        ...(pagination ? { skip: pagination.skip, take: pagination.limit } : { take: 200 }),
      }),
      pagination ? db.lostFoundItem.count({ where: scoped }) : Promise.resolve(0),
    ]);
    // Who else claimed or reported something is not theirs to see.
    const shown = rows.map((r) => ({ ...r, mine: r.reporterProfileId === p.id, claimedByMe: r.claimantProfileId === p.id, reporterProfileId: null, claimantProfileId: null, reportedById: '' }));
    return pagination ? paginated(shown, total, pagination) : shown;
  }
  assertDesk(viewer.perms);
  const [rows, total] = await Promise.all([
    db.lostFoundItem.findMany({
      where,
      orderBy: pagination ? [{ status: 'asc' }, { happenedAt: 'desc' }, { id: 'asc' }] : [{ status: 'asc' }, { happenedAt: 'desc' }],
      ...(pagination ? { skip: pagination.skip, take: pagination.limit } : { take: 300 }),
    }),
    pagination ? db.lostFoundItem.count({ where }) : Promise.resolve(0),
  ]);
  const shown = await withPeople(rows);
  if (!pagination) return shown;
  // Sprint L4: open lost reports on the page carry the open found items that look like them.
  if (f.matches) {
    const found = await matchesFor(shown, f.propertyId);
    return paginated(shown.map((r) => (r.kind === 'LOST' && r.status === 'OPEN' ? { ...r, matches: found.get(r.id) ?? [] } : r)), total, pagination);
  }
  return paginated(shown, total, pagination);
}

/** Desk rows with the reporter and claimant named. */
async function withPeople<T extends { reporterProfileId: string | null; claimantProfileId: string | null }>(rows: T[]) {
  const ids = [...new Set(rows.flatMap((r) => [r.reporterProfileId, r.claimantProfileId]).filter((x): x is string => !!x))];
  const people = new Map((await db.studentProfile.findMany({ where: { id: { in: ids } }, select: { id: true, employeeCode: true, user: { select: { name: true, phone: true } } } })).map((p) => [p.id, { name: p.user.name, phone: p.user.phone, employeeCode: p.employeeCode }]));
  return rows.map((r) => ({ ...r, reporter: r.reporterProfileId ? people.get(r.reporterProfileId) ?? null : null, claimant: r.claimantProfileId ? people.get(r.claimantProfileId) ?? null : null }));
}

/** Words of three letters or more, as the desk's match hint splits a title. */
const titleWords = (s: string) => new Set(s.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length >= 3));

/**
 * Up to four open found items for each open lost report (Sprint L4): the same
 * category, or a word of the title in common — the web's hint, which read up to
 * 300 open found items to work it out. Only found items that could match are
 * read, newest first, in the block chosen (and those with none).
 */
async function matchesFor(rows: { id: string; kind: string; status: string; title: string; category: string | null }[], propertyId?: string) {
  const lost = rows.filter((r) => r.kind === 'LOST' && r.status === 'OPEN');
  const out = new Map<string, Awaited<ReturnType<typeof withPeople<LostFoundItem>>>>();
  if (lost.length === 0) return out;
  const words = [...new Set(lost.flatMap((r) => [...titleWords(r.title)]))].slice(0, 200);
  const categories = [...new Set(lost.flatMap((r) => (r.category ? [r.category] : [])))];
  const like: Prisma.LostFoundItemWhereInput[] = [...(categories.length ? [{ category: { in: categories } }] : []), ...words.map((w) => ({ title: { contains: w, mode: 'insensitive' as const } }))];
  if (like.length === 0) return out;
  const candidates = await withPeople(
    await db.lostFoundItem.findMany({
      where: { kind: 'FOUND', status: 'OPEN', ...(propertyId ? { OR: [{ propertyId }, { propertyId: null }] } : {}), AND: [{ OR: like }] },
      orderBy: [{ happenedAt: 'desc' }, { id: 'asc' }],
      take: 500,
    }),
  );
  const candidateWords = new Map(candidates.map((c) => [c.id, titleWords(c.title)]));
  for (const r of lost) {
    const mine = titleWords(r.title);
    out.set(r.id, candidates.filter((c) => (r.category && c.category === r.category) || [...candidateWords.get(c.id)!].some((w) => mine.has(w))).slice(0, 4));
  }
  return out;
}

/** "This is mine": a found item waits for the desk to check and hand it over. */
export async function claimItem(userId: string, id: string) {
  const p = await profileOf(userId);
  const item = await db.lostFoundItem.findFirst({ where: { id } });
  if (!item || item.kind !== 'FOUND') throw new NotFoundError('Item not found');
  if (item.status !== 'OPEN') throw new ConflictError('Someone has already claimed it — ask at the desk');
  const claimed = await db.lostFoundItem.updateMany({ where: { id, status: 'OPEN' }, data: { status: 'CLAIMED', claimantProfileId: p.id, claimedAt: new Date() } });
  if (!claimed.count) throw new ConflictError('Someone has already claimed it — ask at the desk');
  inBackground('push: lost and found claim', () => notifyLostFound(getTenantIdOrThrow(), id, 'CLAIM'));
  return { ok: true };
}

/**
 * The desk settles an item: RETURNED to its owner (the claimant, or someone
 * the desk names), back to OPEN when a claim was wrong, or CLOSED (disposed,
 * or a lost report given up).
 */
export async function settleItem(id: string, to: 'RETURNED' | 'OPEN' | 'CLOSED', actorId: string, opts: { claimantProfileId?: string | null; note?: string | null }) {
  const item = await db.lostFoundItem.findFirst({ where: { id } });
  if (!item) throw new NotFoundError('Item not found');
  if (to === 'RETURNED') {
    const owner = opts.claimantProfileId ?? item.claimantProfileId ?? item.reporterProfileId;
    if (!owner) throw new BadRequestError('Say who it went back to');
    if (opts.claimantProfileId && !(await db.studentProfile.findFirst({ where: { id: opts.claimantProfileId }, select: { id: true } }))) throw new NotFoundError('Employee not found');
    await db.lostFoundItem.update({ where: { id }, data: { status: 'RETURNED', claimantProfileId: owner, returnedAt: new Date(), returnedById: actorId, ...(opts.note ? { note: opts.note } : {}) } });
    inBackground('push: lost and found returned', () => notifyLostFound(getTenantIdOrThrow(), id, 'RETURNED'));
  } else if (to === 'OPEN') {
    await db.lostFoundItem.update({ where: { id }, data: { status: 'OPEN', claimantProfileId: null, claimedAt: null, ...(opts.note ? { note: opts.note } : {}) } });
  } else {
    await db.lostFoundItem.update({ where: { id }, data: { status: 'CLOSED', ...(opts.note ? { note: opts.note } : {}) } });
  }
  return db.lostFoundItem.findFirst({ where: { id } });
}
