import { Prisma } from '@prisma/client';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';
import { inBackground, notifyLaundryReady } from '../notifications/notifications.service';
import { paginated, type Pagination } from '../../lib/pagination';

/**
 * Laundry (Sprint 3, TEPL). An employee asks for a pickup; the desk takes the
 * bag in (with its bag number); bags go to the laundry vendor in a batch;
 * the batch comes back and the bags are ready; the employee collects. The
 * desk is the housekeeping supervisor (MANAGE_HOUSEKEEPING). A provider's
 * own tracking can replace the batch steps later.
 */

const OPEN = ['REQUESTED', 'RECEIVED', 'IN_PROCESS', 'READY'];

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;
}

export async function requestPickup(userId: string, input: { items: number; note?: string | null }) {
  const p = await profileOf(userId);
  const open = await db.laundryOrder.count({ where: { studentProfileId: p.id, status: { in: OPEN } } });
  if (open >= 3) throw new ConflictError('You already have 3 bags in the laundry');
  return db.laundryOrder.create({ data: { tenantId: getTenantIdOrThrow(), propertyId: p.propertyId, studentProfileId: p.id, items: input.items, note: input.note ?? null } });
}

export async function myOrders(userId: string) {
  const p = await profileOf(userId);
  return db.laundryOrder.findMany({ where: { studentProfileId: p.id }, orderBy: { requestedAt: 'desc' }, take: 30 });
}

export async function cancelMine(userId: string, id: string) {
  const p = await profileOf(userId);
  const o = await db.laundryOrder.findFirst({ where: { id, studentProfileId: p.id } });
  if (!o) throw new NotFoundError('Not found');
  if (o.status !== 'REQUESTED') throw new ConflictError('The desk has it already — ask them');
  return db.laundryOrder.update({ where: { id }, data: { status: 'CANCELLED' } });
}

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

const deskWhere = (f: { status?: string; propertyId?: string }) => ({ ...(f.status ? { status: f.status } : { status: { in: OPEN } }), ...(f.propertyId ? { propertyId: f.propertyId } : {}) });

async function withPeople<T extends { studentProfileId: string }>(rows: T[]) {
  const people = new Map((await db.studentProfile.findMany({ where: { id: { in: [...new Set(rows.map((r) => r.studentProfileId))] } }, select: deskInclude.student.select })).map((p) => [p.id, p]));
  return rows.map((r) => ({ ...r, student: people.get(r.studentProfileId) ?? null }));
}

export async function deskOrders(f: { status?: string; propertyId?: string }) {
  const rows = await db.laundryOrder.findMany({
    where: deskWhere(f),
    orderBy: { requestedAt: 'asc' },
    take: 1000,
  });
  return withPeople(rows);
}

/**
 * The desk's bags a page at a time (Sprint L2), oldest request first as before.
 * `q` searches what the desk's box always matched on the page — name, employee
 * ID, room and bag number — across the whole list instead.
 */
export async function pageDeskOrders(f: { status?: string; propertyId?: string; q?: string }, pagination: Pagination) {
  let where: Prisma.LaundryOrderWhereInput = deskWhere(f);
  if (f.q) {
    const contains = { contains: f.q, mode: 'insensitive' as const };
    const owners = await db.studentProfile.findMany({
      where: { ...(f.propertyId ? { propertyId: f.propertyId } : {}), OR: [{ user: { name: contains } }, { employeeCode: contains }, { bed: { room: { number: contains } } }] },
      select: { id: true },
      take: 500,
    });
    where = { AND: [where, { OR: [{ bagNo: contains }, { studentProfileId: { in: owners.map((o) => o.id) } }] }] };
  }
  const [rows, total] = await Promise.all([
    db.laundryOrder.findMany({ where, orderBy: [{ requestedAt: 'asc' }, { id: 'asc' }], skip: pagination.skip, take: pagination.limit }),
    db.laundryOrder.count({ where }),
  ]);
  return paginated(await withPeople(rows), total, pagination);
}

/** The desk takes a bag in, with its number. Also for walk-ups who never asked in the app. */
export async function receive(input: { orderId?: string; studentProfileId?: string; items?: number; bagNo: string; note?: string | null }, actorId: string) {
  if (input.orderId) {
    const o = await db.laundryOrder.findFirst({ where: { id: input.orderId } });
    if (!o) throw new NotFoundError('Not found');
    if (o.status !== 'REQUESTED') throw new ConflictError('Already received');
    return db.laundryOrder.update({ where: { id: o.id }, data: { status: 'RECEIVED', bagNo: input.bagNo, receivedAt: new Date(), handledById: actorId, ...(input.items ? { items: input.items } : {}) } });
  }
  if (!input.studentProfileId || !input.items) throw new BadRequestError('Say whose bag it is and how many items');
  const p = await db.studentProfile.findFirst({ where: { id: input.studentProfileId }, select: { id: true, propertyId: true } });
  if (!p) throw new NotFoundError('Employee not found');
  return db.laundryOrder.create({ data: { tenantId: getTenantIdOrThrow(), propertyId: p.propertyId, studentProfileId: p.id, items: input.items, bagNo: input.bagNo, note: input.note ?? null, status: 'RECEIVED', receivedAt: new Date(), handledById: actorId } });
}

/** Received bags go to the vendor together. */
export async function sendBatch(orderIds: string[], vendorId: string | null, actorId: string, propertyId?: string) {
  const orders = await db.laundryOrder.findMany({ where: { id: { in: orderIds }, status: 'RECEIVED' }, select: { id: true } });
  if (orders.length !== orderIds.length) throw new ConflictError('Only received bags can be sent');
  if (vendorId && !(await db.vendor.findFirst({ where: { id: vendorId }, select: { id: true } }))) throw new NotFoundError('Vendor not found');
  const tenantId = getTenantIdOrThrow();
  return db.$transaction(async (tx) => {
    const batch = await tx.laundryBatch.create({ data: { tenantId, propertyId: propertyId ?? null, vendorId, sentById: actorId } });
    await tx.laundryOrder.updateMany({ where: { id: { in: orderIds } }, data: { status: 'IN_PROCESS', batchId: batch.id } });
    return tx.laundryBatch.findFirstOrThrow({ where: { id: batch.id }, include: { orders: true } });
  });
}

const batchInclude = { orders: { select: { id: true, bagNo: true, items: true, status: true, studentProfileId: true } } } as const;

export function batches(status?: string, propertyId?: string) {
  return db.laundryBatch.findMany({ where: { ...(status ? { status } : {}), ...(propertyId ? { propertyId } : {}) }, include: batchInclude, orderBy: { sentAt: 'desc' }, take: 100 });
}

/**
 * Batches a page at a time (Sprint L2), newest first, so older ones stay
 * reachable. Each bag names its owner, which the desk used to look up in its
 * full list of open bags — a list it no longer holds.
 */
export async function pageBatches(status: string | undefined, propertyId: string | undefined, pagination: Pagination) {
  const where = { ...(status ? { status } : {}), ...(propertyId ? { propertyId } : {}) };
  const [rows, total] = await Promise.all([
    db.laundryBatch.findMany({ where, include: batchInclude, orderBy: [{ sentAt: 'desc' }, { id: 'desc' }], skip: pagination.skip, take: pagination.limit }),
    db.laundryBatch.count({ where }),
  ]);
  const owners = await withPeople(rows.flatMap((b) => b.orders));
  const byId = new Map(owners.map((o) => [o.id, o]));
  return paginated(rows.map((b) => ({ ...b, orders: b.orders.map((o) => byId.get(o.id) ?? { ...o, student: null }) })), total, pagination);
}

/** The batch is back: every bag in it is ready, and its owner is told. */
export async function returnBatch(id: string) {
  const b = await db.laundryBatch.findFirst({ where: { id }, include: { orders: { select: { id: true, status: true } } } });
  if (!b) throw new NotFoundError('Batch not found');
  if (b.status !== 'SENT') throw new ConflictError('This batch is already back');
  const now = new Date();
  await db.$transaction([
    db.laundryBatch.update({ where: { id }, data: { status: 'RETURNED', returnedAt: now } }),
    db.laundryOrder.updateMany({ where: { batchId: id, status: 'IN_PROCESS' }, data: { status: 'READY', readyAt: now } }),
  ]);
  const tenantId = getTenantIdOrThrow();
  const ready = b.orders.filter((o) => o.status === 'IN_PROCESS').map((o) => o.id);
  inBackground('push: laundry ready', () => notifyLaundryReady(tenantId, ready));
  return db.laundryBatch.findFirstOrThrow({ where: { id }, include: { orders: true } });
}

export async function deliver(id: string, actorId: string) {
  const o = await db.laundryOrder.findFirst({ where: { id } });
  if (!o) throw new NotFoundError('Not found');
  if (o.status !== 'READY') throw new ConflictError('This bag is not back yet');
  return db.laundryOrder.update({ where: { id }, data: { status: 'DELIVERED', deliveredAt: new Date(), handledById: actorId } });
}

/** The desk's pickers: the laundry vendors. */
export function vendors() {
  return db.vendor.findMany({ where: { isArchived: false }, select: { id: true, name: true, trade: true, phone: true, note: true, isArchived: true }, orderBy: { name: 'asc' }, take: 500 });
}

export { findEmployees } from '../students/employee-lookup';

/** Turnaround over N days: bags, and average hours from received to ready to delivered. */
export async function stats(days: number, propertyId?: string) {
  const since = new Date(Date.now() - days * 86_400_000);
  const rows = await db.laundryOrder.findMany({ where: { requestedAt: { gte: since }, status: { not: 'CANCELLED' }, ...(propertyId ? { propertyId } : {}) }, select: { status: true, items: true, receivedAt: true, readyAt: true, deliveredAt: true } });
  const hours = (a: Date | null, b: Date | null) => (a && b ? (b.getTime() - a.getTime()) / 3_600_000 : null);
  const avg = (xs: (number | null)[]) => {
    const v = xs.filter((x): x is number => x !== null);
    return v.length ? Math.round((v.reduce((s, x) => s + x, 0) / v.length) * 10) / 10 : null;
  };
  return {
    days,
    bags: rows.length,
    items: rows.reduce((n, r) => n + r.items, 0),
    delivered: rows.filter((r) => r.status === 'DELIVERED').length,
    open: rows.filter((r) => OPEN.includes(r.status)).length,
    avgHoursAtVendor: avg(rows.map((r) => hours(r.receivedAt, r.readyAt))),
    avgHoursToDeliver: avg(rows.map((r) => hours(r.receivedAt, r.deliveredAt))),
  };
}

// ── Sprint 7 (TEPL): the provider's feed ────────────────────────────────────

/**
 * The laundry provider pushes bag status with a LAUNDRY device key, by the
 * bag number the desk wrote down: PICKED_UP (it is with them), READY (back at
 * the desk, washed) or DELIVERED (they took it to the room). A bag only moves
 * forward, so the same update twice changes nothing. A batch whose bags are
 * all back is marked returned; owners are told their bag is ready, as when
 * the desk marks a batch back.
 */
export const FEED_STATUSES = ['PICKED_UP', 'READY', 'DELIVERED'] as const;
export type FeedStatus = (typeof FEED_STATUSES)[number];
const RANK: Record<string, number> = { RECEIVED: 1, IN_PROCESS: 2, READY: 3, DELIVERED: 4 };
const TARGET: Record<FeedStatus, string> = { PICKED_UP: 'IN_PROCESS', READY: 'READY', DELIVERED: 'DELIVERED' };

export interface FeedUpdate {
  bagNo: string;
  status: FeedStatus;
  at?: Date;
}

export async function providerFeed(updates: FeedUpdate[], device: { id: string; propertyId: string | null }) {
  const tenantId = getTenantIdOrThrow();
  const bagNos = [...new Set(updates.map((u) => u.bagNo.trim()))];
  const open = await db.laundryOrder.findMany({
    where: { OR: bagNos.map((b) => ({ bagNo: { equals: b, mode: 'insensitive' as const } })), status: { in: ['RECEIVED', 'IN_PROCESS', 'READY'] }, ...(device.propertyId ? { propertyId: device.propertyId } : {}) },
    orderBy: { receivedAt: 'asc' },
    select: { id: true, bagNo: true, status: true, batchId: true },
  });
  // A bag number is reused once delivered: the oldest open bag with it is the one meant.
  const byBag = new Map<string, (typeof open)[number]>();
  for (const o of open) if (o.bagNo && !byBag.has(o.bagNo.toLowerCase())) byBag.set(o.bagNo.toLowerCase(), o);
  const errors: { row: number; message: string }[] = [];
  const nowReady: string[] = [];
  const batches = new Set<string>();
  let moved = 0;
  let unchanged = 0;
  const now = new Date();
  for (const [i, u] of updates.entries()) {
    const row = i + 1;
    const o = byBag.get(u.bagNo.trim().toLowerCase());
    if (!o) {
      errors.push({ row, message: `No open bag ${u.bagNo} at the desk` });
      continue;
    }
    const to = TARGET[u.status];
    if (RANK[to] <= RANK[o.status]) {
      unchanged++;
      continue;
    }
    const at = u.at && u.at <= now ? u.at : now;
    const data: Prisma.LaundryOrderUpdateInput = { status: to, ...(RANK[o.status] < RANK.READY && RANK[to] >= RANK.READY ? { readyAt: at } : {}), ...(to === 'DELIVERED' ? { deliveredAt: at } : {}) };
    await db.laundryOrder.update({ where: { id: o.id }, data });
    if (to === 'READY') nowReady.push(o.id);
    if (o.batchId) batches.add(o.batchId);
    o.status = to;
    moved++;
  }
  // A batch is back once none of its bags is still with the provider.
  for (const id of batches) {
    const still = await db.laundryOrder.count({ where: { batchId: id, status: { in: ['RECEIVED', 'IN_PROCESS'] } } });
    if (!still) await db.laundryBatch.updateMany({ where: { id, status: 'SENT' }, data: { status: 'RETURNED', returnedAt: now } });
  }
  if (nowReady.length) inBackground('push: laundry ready (feed)', () => notifyLaundryReady(tenantId, nowReady));
  await db.integrationRun.create({ data: { tenantId, kind: 'LAUNDRY', source: 'FEED', deviceId: device.id, received: updates.length, accepted: moved + unchanged, failed: errors.length, errors: errors.slice(0, 200) as Prisma.InputJsonValue } });
  return { received: updates.length, moved, unchanged, failed: errors.length, errors };
}

/** The desk's view of the feed: its recent runs and the provider keys. */
export async function feedRuns() {
  const [runs, keys] = await Promise.all([
    db.integrationRun.findMany({ where: { kind: 'LAUNDRY' }, orderBy: { at: 'desc' }, take: 30 }),
    db.biometricDevice.findMany({ where: { purpose: 'LAUNDRY' }, select: { id: true, name: true, serialNumber: true, propertyId: true, isActive: true, lastSeenAt: true, createdAt: true }, orderBy: { createdAt: 'asc' } }),
  ]);
  return { runs, keys };
}
