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

/**
 * Cleaning (Sprint 2–3 plan, built Sprint 3, TEPL): areas with how often they
 * are cleaned; each day's tasks made from that rota; housekeepers tick their
 * own tasks, with a photo; a task not done by the end of its day is missed,
 * and the supervisor hears of it.
 *
 * Supervisors hold MANAGE_HOUSEKEEPING; housekeepers hold WORK_TASKS and see
 * only what is theirs (or nobody's, to pick up).
 */

export const KINDS = ['ROOM', 'CORRIDOR', 'RESTROOM', 'VERANDA', 'COMMON', 'OUTDOOR', 'OTHER'] as const;
export const FREQUENCIES = ['TWICE_DAILY', 'DAILY', 'WEEKLY', 'MONTHLY'] as const;

const IST_MS = 330 * 60_000;
const DAY_MS = 86_400_000;
export const istToday = (now = new Date()) => new Date(now.getTime() + IST_MS).toISOString().slice(0, 10);
const asDate = (ymd: string) => new Date(`${ymd}T00:00:00.000Z`);

export interface Viewer {
  userId: string;
  role: Role;
  perms: Permission[];
}
const supervises = (v: Viewer) => v.perms.includes('MANAGE_HOUSEKEEPING');
export function assertSupervisor(v: Viewer) {
  if (!supervises(v)) throw new ForbiddenError('Requires permission: MANAGE_HOUSEKEEPING');
}
export function assertHousekeeping(v: Viewer) {
  if (!supervises(v) && !v.perms.includes('WORK_TASKS')) throw new ForbiddenError('Requires permission: MANAGE_HOUSEKEEPING or WORK_TASKS');
}

// ── Areas ───────────────────────────────────────────────────────────────────

export interface AreaInput {
  propertyId: string;
  roomId?: string | null;
  name: string;
  kind: string;
  floor?: number | null;
  frequency: string;
  weekday?: number | null;
  monthDay?: number | null;
  defaultAssigneeId?: string | null;
  checklist?: string[];
  isActive?: boolean;
}

function checkRota(a: { frequency: string; weekday?: number | null; monthDay?: number | null }) {
  if (a.frequency === 'WEEKLY' && !a.weekday) throw new BadRequestError('Choose the day of the week');
  if (a.frequency === 'MONTHLY' && !a.monthDay) throw new BadRequestError('Choose the day of the month');
}

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_HOUSEKEEPING')) throw new BadRequestError('Choose a housekeeper (a role with “Work the tasks handed to them”)');
}

export function listAreas(propertyId?: string, includeInactive = false) {
  return db.cleaningArea.findMany({
    where: { ...(propertyId ? { propertyId } : {}), ...(includeInactive ? {} : { isActive: true }) },
    orderBy: [{ floor: 'asc' }, { name: 'asc' }],
    take: 2000,
  });
}

export async function createArea(input: AreaInput) {
  checkRota(input);
  await checkAssignee(input.defaultAssigneeId);
  if (!(await db.property.findFirst({ where: { id: input.propertyId }, select: { id: true } }))) throw new NotFoundError('Property not found');
  if (input.roomId && !(await db.room.findFirst({ where: { id: input.roomId, propertyId: input.propertyId }, select: { id: true } }))) throw new NotFoundError('Room not found in that property');
  return db.cleaningArea.create({ data: { ...input, checklist: input.checklist ?? [], tenantId: getTenantIdOrThrow() } });
}

export async function updateArea(id: string, input: Partial<AreaInput>) {
  const a = await db.cleaningArea.findFirst({ where: { id } });
  if (!a) throw new NotFoundError('Area not found');
  checkRota({ frequency: input.frequency ?? a.frequency, weekday: input.weekday !== undefined ? input.weekday : a.weekday, monthDay: input.monthDay !== undefined ? input.monthDay : a.monthDay });
  await checkAssignee(input.defaultAssigneeId);
  if (input.roomId && !(await db.room.findFirst({ where: { id: input.roomId, propertyId: a.propertyId }, select: { id: true } }))) throw new NotFoundError('Room not found in that property');
  const { propertyId: _ignored, ...rest } = input;
  return db.cleaningArea.update({ where: { id }, data: rest });
}

/** Every room of a property as an area, once: the quick start for a new block. */
export async function addRoomsAsAreas(propertyId: string, frequency: string, defaultAssigneeId?: string | null) {
  await checkAssignee(defaultAssigneeId);
  const rooms = await db.room.findMany({ where: { propertyId, archivedAt: null }, select: { id: true, number: true, floor: true } });
  const have = new Set((await db.cleaningArea.findMany({ where: { propertyId, roomId: { not: null } }, select: { roomId: true } })).map((a) => a.roomId));
  const tenantId = getTenantIdOrThrow();
  const data = rooms.filter((r) => !have.has(r.id)).map((r) => ({ tenantId, propertyId, roomId: r.id, name: `Room ${r.number}`, kind: 'ROOM', floor: r.floor, frequency, defaultAssigneeId: defaultAssigneeId ?? null, checklist: ['Floor swept and mopped', 'Bin emptied', 'Washbasin wiped'] }));
  if (data.length) await db.cleaningArea.createMany({ data });
  return { added: data.length, skipped: rooms.length - data.length };
}

/** The supervisor's pickers: who can be handed cleaning, and the blocks. */
export async function options() {
  const [users, properties] = 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.property.findMany({ select: { id: true, name: true }, orderBy: { name: 'asc' } }),
  ]);
  const staff = users
    .map((u) => ({ u, perms: effectivePermissions(u.role, u.customRole?.permissions) }))
    .filter(({ perms }) => perms.includes('WORK_TASKS') || perms.includes('MANAGE_HOUSEKEEPING'))
    .map(({ u, perms }) => ({ id: u.id, name: u.name, roleName: u.customRole?.name ?? null, supervisor: perms.includes('MANAGE_HOUSEKEEPING') }));
  return { staff, properties };
}

// ── Tasks ───────────────────────────────────────────────────────────────────

/** The slots an area is due in on a day (India time), from its rota. */
export function slotsDue(a: { frequency: string; weekday: number | null; monthDay: number | null }, day: string): string[] {
  const d = asDate(day);
  const weekday = ((d.getUTCDay() + 6) % 7) + 1;
  if (a.frequency === 'TWICE_DAILY') return ['MORNING', 'EVENING'];
  if (a.frequency === 'DAILY') return ['DAY'];
  if (a.frequency === 'WEEKLY') return weekday === a.weekday ? ['DAY'] : [];
  if (a.frequency === 'MONTHLY') return d.getUTCDate() === a.monthDay ? ['DAY'] : [];
  return [];
}

/**
 * Make a day's tasks from the rota. Safe to run again: each area-day-slot
 * exists once. An area added later than the day owes nothing for it, so
 * opening an old day does not invent missed cleans.
 */
export async function generateDay(day: string, propertyId?: string) {
  const dayEnd = asDate(day).getTime() - IST_MS + DAY_MS;
  const areas = (await listAreas(propertyId)).filter((a) => a.createdAt.getTime() < dayEnd);
  const tenantId = getTenantIdOrThrow();
  const data: Prisma.CleaningTaskCreateManyInput[] = [];
  for (const a of areas) for (const slot of slotsDue(a, day)) data.push({ tenantId, propertyId: a.propertyId, areaId: a.id, dueDate: asDate(day), slot, assigneeId: a.defaultAssigneeId });
  const made = data.length ? await db.cleaningTask.createMany({ data, skipDuplicates: true }) : { count: 0 };
  return { made: made.count };
}

const taskInclude = { area: { select: { id: true, name: true, kind: true, floor: true, checklist: true, propertyId: true, roomId: true } } } as const;

/** A day's board: every task, who has it and where it stands. */
export async function board(day: string, f: { propertyId?: string; assigneeId?: string; status?: string }) {
  await generateDay(day, f.propertyId);
  const tasks = await db.cleaningTask.findMany({
    where: { dueDate: asDate(day), ...(f.propertyId ? { propertyId: f.propertyId } : {}), ...(f.assigneeId ? { assigneeId: f.assigneeId === 'none' ? null : f.assigneeId } : {}), ...(f.status ? { status: f.status } : {}) },
    include: taskInclude,
    orderBy: [{ area: { floor: 'asc' } }, { area: { name: 'asc' } }, { slot: 'asc' }],
    take: 3000,
  });
  const people = new Map((await db.user.findMany({ where: { id: { in: [...new Set(tasks.flatMap((t) => [t.assigneeId, t.doneById]).filter((x): x is string => !!x))] } }, select: { id: true, name: true } })).map((u) => [u.id, u.name]));
  const count = (s: string) => tasks.filter((t) => t.status === s).length;
  return {
    day,
    summary: { total: tasks.length, done: count('DONE'), pending: count('PENDING'), missed: count('MISSED'), skipped: count('SKIPPED') },
    tasks: tasks.map((t) => ({ ...t, assignee: t.assigneeId ? { id: t.assigneeId, name: people.get(t.assigneeId) ?? '' } : null, doneBy: t.doneById ? people.get(t.doneById) ?? null : null })),
  };
}

/** A housekeeper's own list for the day: theirs, and anything nobody has. */
export async function myTasks(userId: string, day: string) {
  await generateDay(day);
  return db.cleaningTask.findMany({
    where: { dueDate: asDate(day), OR: [{ assigneeId: userId }, { assigneeId: null }] },
    include: taskInclude,
    orderBy: [{ status: 'asc' }, { area: { floor: 'asc' } }, { area: { name: 'asc' } }],
    take: 500,
  });
}

/** Mark done (or skipped, or back to pending). A housekeeper only touches theirs or nobody's; a past day is the supervisor's. */
export async function setTaskStatus(id: string, v: Viewer, status: 'DONE' | 'PENDING' | 'SKIPPED', note?: string | null) {
  const t = await db.cleaningTask.findFirst({ where: { id } });
  if (!t) throw new NotFoundError('Task not found');
  if (!supervises(v)) {
    if (t.assigneeId && t.assigneeId !== v.userId) throw new ForbiddenError('This task is someone else’s');
    if (status === 'SKIPPED') throw new ForbiddenError('Only the supervisor can skip a task');
    if (t.dueDate.toISOString().slice(0, 10) !== istToday()) throw new ConflictError('Only today’s tasks can be ticked here');
  }
  return db.cleaningTask.update({
    where: { id },
    data: {
      status,
      ...(status === 'DONE' ? { doneAt: new Date(), doneById: v.userId, assigneeId: t.assigneeId ?? v.userId } : { doneAt: null, doneById: null }),
      ...(note !== undefined ? { note } : {}),
    },
    include: taskInclude,
  });
}

export async function assignTask(id: string, assigneeId: string | null) {
  await checkAssignee(assigneeId);
  const t = await db.cleaningTask.findFirst({ where: { id } });
  if (!t) throw new NotFoundError('Task not found');
  return db.cleaningTask.update({ where: { id }, data: { assigneeId }, include: taskInclude });
}

/** How often each area was actually cleaned over the last N days. Today counts what is already settled; what is still to do today is not yet late. */
export async function frequencyReport(days: number, propertyId?: string) {
  const since = asDate(istToday(new Date(Date.now() - (days - 1) * DAY_MS)));
  const today = asDate(istToday());
  const tasks = (await db.cleaningTask.findMany({ where: { dueDate: { gte: since, lte: today }, ...(propertyId ? { propertyId } : {}) }, select: { areaId: true, status: true, doneAt: true, dueDate: true } })).filter(
    (t) => !(t.status === 'PENDING' && t.dueDate.getTime() === today.getTime()),
  );
  const areas = await listAreas(propertyId, true);
  return areas.map((a) => {
    const mine = tasks.filter((t) => t.areaId === a.id);
    const done = mine.filter((t) => t.status === 'DONE');
    const last = done.reduce<Date | null>((m, t) => (t.doneAt && (!m || t.doneAt > m) ? t.doneAt : m), null);
    return { areaId: a.id, name: a.name, kind: a.kind, floor: a.floor, frequency: a.frequency, due: mine.length, done: done.length, missed: mine.filter((t) => t.status === 'MISSED').length, rate: mine.length ? Math.round((done.length / mine.length) * 100) : null, lastDone: last };
  });
}

/**
 * The hourly pass: today's tasks for every tenant with cleaning on, and
 * yesterday's (or older) still pending marked missed, the supervisors told
 * once per day.
 */
export async function runCleaningPass(now = new Date()): Promise<void> {
  const tenants = await prismaUnscoped.cleaningArea.groupBy({ by: ['tenantId'], where: { isActive: true } });
  const today = istToday(now);
  for (const { tenantId } of tenants) {
    if (!(await tenantHasFeature(tenantId, 'cleaning'))) continue;
    await runWithTenantContext({ userId: 'system:cleaning', role: Role.HOSTEL_ADMIN, tenantId }, async () => {
      await generateDay(today);
      const missed = await db.cleaningTask.updateMany({ where: { status: 'PENDING', dueDate: { lt: asDate(today) } }, data: { status: 'MISSED' } });
      if (missed.count) inBackground('push: cleaning missed', () => notifyCleaningMissed(tenantId, today, missed.count));
    });
  }
}
