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

/**
 * Room inventory (Sprint 3, TEPL): the live register of what is in each room
 * and its state, periodic room audits that update it, work orders raised
 * automatically for anything found broken or missing, and the general store.
 *
 * The register is made from each property's move-in checklist template (the
 * same items the move-in check uses), then kept up by audits.
 */

export const ASSET_STATUSES = ['WORKING', 'NEEDS_REPAIR', 'MISSING', 'DISPOSED'] as const;
export const STORE_CATEGORIES = ['LINEN', 'CLEANING', 'ELECTRICAL', 'PLUMBING', 'STATIONERY', 'FURNITURE', 'OTHER'] as const;

// ── The register ────────────────────────────────────────────────────────────

/** People's names by id, for the "by whom" on audits and stock movements. */
async function namesOf(ids: (string | null | undefined)[]) {
  const want = [...new Set(ids.filter((x): x is string => !!x))];
  const users = want.length ? await db.user.findMany({ where: { id: { in: want } }, select: { id: true, name: true } }) : [];
  return new Map(users.map((u) => [u.id, u.name]));
}

export async function roomRegister(roomId: string) {
  const room = await db.room.findFirst({ where: { id: roomId }, select: { id: true, number: true, floor: true, type: true, propertyId: true } });
  if (!room) throw new NotFoundError('Room not found');
  const [assets, lastAudit, openOrders] = await Promise.all([
    db.roomAsset.findMany({ where: { roomId, status: { not: 'DISPOSED' } }, orderBy: { name: 'asc' } }),
    db.roomAudit.findFirst({ where: { roomId }, orderBy: { auditedAt: 'desc' } }),
    db.workOrder.findMany({ where: { roomId, status: { in: ['OPEN', 'IN_PROGRESS'] } }, orderBy: { createdAt: 'desc' } }),
  ]);
  const names = await namesOf([lastAudit?.auditedById]);
  return { room, assets, lastAudit: lastAudit ? { ...lastAudit, auditedBy: names.get(lastAudit.auditedById) ?? null } : null, openOrders: await orderInclude(openOrders) };
}

/** Rooms with their register counts, for the overview: how many items need repair or are missing, and when last audited. */
export async function registerOverview(propertyId?: string) {
  const rooms = await db.room.findMany({ where: { archivedAt: null, ...(propertyId ? { propertyId } : {}) }, select: { id: true, number: true, floor: true, type: true, propertyId: true }, orderBy: [{ floor: 'asc' }, { number: 'asc' }], take: 3000 });
  const ids = rooms.map((r) => r.id);
  const [counts, audits] = await Promise.all([
    db.roomAsset.groupBy({ by: ['roomId', 'status'], where: { roomId: { in: ids } }, _count: { _all: true } }),
    db.roomAudit.groupBy({ by: ['roomId'], where: { roomId: { in: ids } }, _max: { auditedAt: true } }),
  ]);
  const lastAudit = new Map(audits.map((a) => [a.roomId, a._max.auditedAt]));
  return rooms.map((r) => {
    const c = (s: string) => counts.find((x) => x.roomId === r.id && x.status === s)?._count._all ?? 0;
    return { ...r, items: c('WORKING') + c('NEEDS_REPAIR') + c('MISSING'), needsRepair: c('NEEDS_REPAIR'), missing: c('MISSING'), lastAuditedAt: lastAudit.get(r.id) ?? null };
  });
}

/** Make the register for rooms that have none yet, from the property's checklist template for each room type. */
export async function buildRegister(propertyId: string) {
  const rooms = await db.room.findMany({ where: { propertyId, archivedAt: null }, select: { id: true, type: true } });
  const templates = await db.roomAssetTemplate.findMany({ where: { propertyId } });
  const byType = new Map(templates.map((t) => [t.roomType, t.items as { key: string; name: string }[]]));
  const have = new Set((await db.roomAsset.groupBy({ by: ['roomId'], where: { propertyId } })).map((r) => r.roomId));
  const tenantId = getTenantIdOrThrow();
  const data: Prisma.RoomAssetCreateManyInput[] = [];
  let noTemplate = 0;
  for (const r of rooms) {
    if (have.has(r.id)) continue;
    const items = byType.get(r.type ?? '') ?? byType.get('');
    if (!items?.length) {
      noTemplate++;
      continue;
    }
    for (const it of items) data.push({ tenantId, propertyId, roomId: r.id, name: it.name, key: it.key });
  }
  if (data.length) await db.roomAsset.createMany({ data });
  return { items: data.length, rooms: new Set(data.map((d) => d.roomId)).size, roomsWithoutTemplate: noTemplate };
}

export async function addAsset(input: { roomId: string; name: string; tag?: string | null; quantity?: number; note?: string | null }) {
  const room = await db.room.findFirst({ where: { id: input.roomId }, select: { propertyId: true } });
  if (!room) throw new NotFoundError('Room not found');
  return db.roomAsset.create({ data: { ...input, propertyId: room.propertyId, tenantId: getTenantIdOrThrow() } });
}

export async function updateAsset(id: string, input: { name?: string; tag?: string | null; quantity?: number; status?: string; note?: string | null }) {
  if (!(await db.roomAsset.findFirst({ where: { id }, select: { id: true } }))) throw new NotFoundError('Item not found');
  return db.roomAsset.update({ where: { id }, data: input });
}

// ── Audits ──────────────────────────────────────────────────────────────────

/**
 * Walk a room: each item's state now. Anything newly found needing repair or
 * missing gets a work order, unless one is already open for it.
 */
export async function auditRoom(roomId: string, items: { assetId: string; status: string; note?: string | null }[], actorId: string, note?: string | null) {
  const room = await db.room.findFirst({ where: { id: roomId }, select: { id: true, number: true, propertyId: true } });
  if (!room) throw new NotFoundError('Room not found');
  const assets = await db.roomAsset.findMany({ where: { roomId, id: { in: items.map((i) => i.assetId) } } });
  if (assets.length !== items.length) throw new BadRequestError('An item is not in this room');
  const byId = new Map(assets.map((a) => [a.id, a]));
  const now = new Date();
  const tenantId = getTenantIdOrThrow();
  const raised: string[] = [];
  for (const it of items) {
    const a = byId.get(it.assetId)!;
    await db.roomAsset.update({ where: { id: a.id }, data: { status: it.status, lastAuditedAt: now, ...(it.note !== undefined ? { note: it.note } : {}) } });
    const broken = it.status === 'NEEDS_REPAIR' || it.status === 'MISSING';
    if (broken && a.status !== it.status) {
      const open = await db.workOrder.findFirst({ where: { assetId: a.id, status: { in: ['OPEN', 'IN_PROGRESS'] } }, select: { id: true } });
      if (!open) {
        const wo = await db.workOrder.create({
          data: { tenantId, propertyId: room.propertyId, roomId, assetId: a.id, title: `${a.name} ${it.status === 'MISSING' ? 'missing' : 'needs repair'} — room ${room.number}`, description: it.note ?? null, source: 'AUDIT', createdById: actorId, priority: it.status === 'MISSING' ? 'HIGH' : 'NORMAL' },
        });
        raised.push(wo.id);
      }
    }
  }
  const audit = await db.roomAudit.create({
    data: { tenantId, propertyId: room.propertyId, roomId, auditedById: actorId, items: items.map((i) => ({ ...i, name: byId.get(i.assetId)!.name })) as Prisma.InputJsonValue, issues: items.filter((i) => i.status === 'NEEDS_REPAIR' || i.status === 'MISSING').length, note: note ?? null },
  });
  return { audit, workOrdersRaised: raised.length };
}

export async function auditHistory(roomId: string) {
  const audits = await db.roomAudit.findMany({ where: { roomId }, orderBy: { auditedAt: 'desc' }, take: 20 });
  const names = await namesOf(audits.map((a) => a.auditedById));
  return audits.map((a) => ({ ...a, auditedBy: names.get(a.auditedById) ?? null }));
}

// ── Work orders ─────────────────────────────────────────────────────────────

export interface Viewer {
  userId: string;
  role: Role;
  perms: Permission[];
}
const runsOrders = (v: Viewer) => v.perms.includes('MANAGE_ROOMS');

async function checkAssignee(id: string | null | undefined) {
  if (!id) return;
  const u = await db.user.findFirst({ where: { id, role: { in: [Role.HOSTEL_ADMIN, Role.WARDEN, Role.MESS_ADMIN] }, deactivatedAt: null }, select: { role: true, customRole: { select: { permissions: true } } } });
  const perms = u ? effectivePermissions(u.role, u.customRole?.permissions) : [];
  if (!perms.includes('WORK_TASKS') && !perms.includes('MANAGE_ROOMS')) throw new BadRequestError('Choose maintenance staff (a role with “Work the tasks handed to them”)');
}

const orderInclude = async <T extends { roomId: string | null; assigneeId: string | null; vendorId: string | null }>(rows: T[]) => {
  const [rooms, users, vendors] = await Promise.all([
    db.room.findMany({ where: { id: { in: rows.map((r) => r.roomId).filter((x): x is string => !!x) } }, select: { id: true, number: true } }),
    db.user.findMany({ where: { id: { in: rows.map((r) => r.assigneeId).filter((x): x is string => !!x) } }, select: { id: true, name: true } }),
    db.vendor.findMany({ where: { id: { in: rows.map((r) => r.vendorId).filter((x): x is string => !!x) } }, select: { id: true, name: true } }),
  ]);
  const rm = new Map(rooms.map((r) => [r.id, r.number]));
  const us = new Map(users.map((u) => [u.id, u]));
  const vs = new Map(vendors.map((v) => [v.id, v]));
  return rows.map((r) => ({ ...r, roomNumber: r.roomId ? rm.get(r.roomId) ?? null : null, assignee: r.assigneeId ? us.get(r.assigneeId) ?? null : null, vendor: r.vendorId ? vs.get(r.vendorId) ?? null : null }));
};

/** The work-order form's pickers: who can be handed one (by the same rule as checkAssignee), and the vendors. */
export async function orderOptions() {
  const [users, vendors] = await Promise.all([
    db.user.findMany({ where: { role: { in: [Role.WARDEN, Role.MESS_ADMIN] }, deactivatedAt: null }, select: { id: true, name: true, role: true, customRole: { select: { name: true, permissions: true } } }, orderBy: { name: 'asc' }, take: 500 }),
    db.vendor.findMany({ where: { isArchived: false }, select: { id: true, name: true, trade: true, phone: true, note: true, isArchived: true }, orderBy: { name: 'asc' }, take: 500 }),
  ]);
  const staff = users
    .filter((u) => {
      const perms = effectivePermissions(u.role, u.customRole?.permissions);
      return perms.includes('WORK_TASKS') || perms.includes('MANAGE_ROOMS');
    })
    .map((u) => ({ id: u.id, name: u.name, role: u.role, roleName: u.customRole?.name ?? null }));
  return { staff, vendors };
}

function orderWhere(v: Viewer, f: { status?: string; propertyId?: string; mine?: boolean }) {
  if (!runsOrders(v) && !v.perms.includes('WORK_TASKS')) throw new ForbiddenError('Requires permission: MANAGE_ROOMS or WORK_TASKS');
  const onlyMine = f.mine || !runsOrders(v);
  return { ...(f.status ? { status: f.status } : { status: { in: ['OPEN', 'IN_PROGRESS'] } }), ...(f.propertyId ? { propertyId: f.propertyId } : {}), ...(onlyMine ? { assigneeId: v.userId } : {}) };
}

export async function listOrders(v: Viewer, f: { status?: string; propertyId?: string; mine?: boolean }) {
  const rows = await db.workOrder.findMany({
    where: orderWhere(v, f),
    orderBy: [{ status: 'asc' }, { priority: 'asc' }, { createdAt: 'desc' }],
    take: 500,
  });
  return orderInclude(rows);
}

/**
 * Work orders a page at a time (Sprint L3), in the same order; the id breaks
 * ties. `overdue` (Sprint L4) counts the open and in-progress ones past due on
 * every page, with the same block and assignee filter.
 */
export async function pageOrders(v: Viewer, f: { status?: string; propertyId?: string; mine?: boolean }, pagination: Pagination, now = new Date()) {
  const where = orderWhere(v, f);
  // Only an open or in-progress order can be overdue; a DONE or CANCELLED filter has none.
  const live = ['OPEN', 'IN_PROGRESS'].filter((s) => !f.status || s === f.status);
  const [rows, total, overdue] = await Promise.all([
    db.workOrder.findMany({ where, orderBy: [{ status: 'asc' }, { priority: 'asc' }, { createdAt: 'desc' }, { id: 'asc' }], skip: pagination.skip, take: pagination.limit }),
    db.workOrder.count({ where }),
    live.length ? db.workOrder.count({ where: { ...where, status: { in: live }, dueBy: { lt: now } } }) : Promise.resolve(0),
  ]);
  return { ...paginated(await orderInclude(rows), total, pagination), overdue };
}

export interface OrderInput {
  title: string;
  description?: string | null;
  roomId?: string | null;
  priority?: string;
  assigneeId?: string | null;
  vendorId?: string | null;
  dueBy?: Date | null;
  cost?: number | null;
  note?: string | null;
}

/** Where the operator keeps no books (Enterprise), a work order carries no cost. */
async function dropCostWhereOff<T extends { cost?: number | null }>(input: T): Promise<T> {
  if (input.cost === undefined || (await tenantHasFeature(getTenantIdOrThrow(), 'expenses'))) return input;
  const { cost: _cost, ...kept } = input;
  return kept as T;
}

/** Every id the client names must be this account's (Sprint 7 hardening). */
async function checkVendor(vendorId: string | null | undefined) {
  if (vendorId && !(await db.vendor.findFirst({ where: { id: vendorId }, select: { id: true } }))) throw new NotFoundError('Vendor not found');
}

export async function createOrder(given: OrderInput, actorId: string, propertyId?: string) {
  const input = await dropCostWhereOff(given);
  await checkAssignee(input.assigneeId);
  await checkVendor(input.vendorId);
  const room = input.roomId ? await db.room.findFirst({ where: { id: input.roomId }, select: { propertyId: true } }) : null;
  if (input.roomId && !room) throw new NotFoundError('Room not found');
  const wo = await db.workOrder.create({ data: { ...input, tenantId: getTenantIdOrThrow(), propertyId: room?.propertyId ?? propertyId ?? null, createdById: actorId } });
  if (wo.assigneeId) inBackground('push: work order', () => notifyWorkOrderAssigned(wo.tenantId, wo.id));
  return (await orderInclude([wo]))[0];
}

/** The office edits anything; the person it is handed to moves it along. Done closes the asset's repair. */
export async function updateOrder(id: string, v: Viewer, given: Partial<OrderInput> & { status?: string }) {
  const input = await dropCostWhereOff(given);
  const wo = await db.workOrder.findFirst({ where: { id } });
  if (!wo) throw new NotFoundError('Work order not found');
  if (!runsOrders(v)) {
    if (wo.assigneeId !== v.userId) throw new ForbiddenError('This work order is someone else’s');
    const allowed = ['status', 'note'];
    if (Object.keys(input).some((k) => !allowed.includes(k))) throw new ForbiddenError('You can update the status and add a note');
    if (input.status && !['IN_PROGRESS', 'DONE'].includes(input.status)) throw new ForbiddenError('You can mark it in progress or done');
  }
  if (['DONE', 'CANCELLED'].includes(wo.status) && input.status && input.status !== 'OPEN') throw new ConflictError('This work order is closed — reopen it first');
  await checkAssignee(input.assigneeId);
  await checkVendor(input.vendorId);
  if (input.roomId && !(await db.room.findFirst({ where: { id: input.roomId }, select: { id: true } }))) throw new NotFoundError('Room not found');
  const updated = await db.workOrder.update({ where: { id }, data: { ...input, ...(input.status === 'DONE' ? { doneAt: new Date() } : input.status === 'OPEN' ? { doneAt: null } : {}) } });
  // Fixed: the item is back in service.
  if (input.status === 'DONE' && wo.assetId) await db.roomAsset.updateMany({ where: { id: wo.assetId, status: 'NEEDS_REPAIR' }, data: { status: 'WORKING' } });
  if (input.assigneeId && input.assigneeId !== wo.assigneeId) inBackground('push: work order', () => notifyWorkOrderAssigned(wo.tenantId, wo.id));
  return (await orderInclude([updated]))[0];
}

// ── The general store ───────────────────────────────────────────────────────

export function listStore(propertyId?: string, includeArchived = false) {
  return db.storeItem.findMany({ where: { ...(includeArchived ? {} : { isArchived: false }), ...(propertyId ? { OR: [{ propertyId }, { propertyId: null }] } : {}) }, orderBy: [{ category: 'asc' }, { name: 'asc' }], take: 1000 });
}

export async function createStoreItem(input: { name: string; unit?: string; category?: string; reorderLevel?: number; propertyId?: string | null }) {
  const clash = await db.storeItem.findFirst({ where: { name: { equals: input.name, mode: 'insensitive' }, isArchived: false, propertyId: input.propertyId ?? null } });
  if (clash) throw new ConflictError('There is already an item by that name');
  if (input.propertyId && !(await db.property.findFirst({ where: { id: input.propertyId }, select: { id: true } }))) throw new NotFoundError('Property not found');
  return db.storeItem.create({ data: { ...input, tenantId: getTenantIdOrThrow() } });
}

export async function updateStoreItem(id: string, input: { name?: string; unit?: string; category?: string; reorderLevel?: number; isArchived?: boolean }) {
  if (!(await db.storeItem.findFirst({ where: { id }, select: { id: true } }))) throw new NotFoundError('Item not found');
  return db.storeItem.update({ where: { id }, data: input });
}

/** Stock in (a purchase) or out (issued). Out cannot take the stock below zero. */
export async function moveStock(id: string, input: { direction: 'IN' | 'OUT'; quantity: number; note?: string | null; issuedTo?: string | null }, actorId: string) {
  const tenantId = getTenantIdOrThrow();
  return db.$transaction(async (tx) => {
    const item = await tx.storeItem.findFirst({ where: { id } });
    if (!item) throw new NotFoundError('Item not found');
    const next = item.quantity + (input.direction === 'IN' ? input.quantity : -input.quantity);
    if (next < 0) throw new ConflictError(`Only ${item.quantity} ${item.unit} in stock`);
    await tx.storeMovement.create({ data: { tenantId, itemId: id, ...input, recordedById: actorId } });
    return tx.storeItem.update({ where: { id }, data: { quantity: next } });
  });
}

export async function storeLedger(id: string) {
  const moves = await db.storeMovement.findMany({ where: { itemId: id }, orderBy: { at: 'desc' }, take: 200 });
  const names = await namesOf(moves.map((m) => m.recordedById));
  return moves.map((m) => ({ ...m, recordedBy: names.get(m.recordedById) ?? null }));
}
