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

/**
 * Discipline (Sprint 2, TEPL): the incident register. Each breach of the
 * rules is recorded with what happened, when, who saw it and what was done,
 * and kept on the employee's history. Three or more in 90 days marks a
 * repeat offender, which the register and the report call out.
 */

export const CATEGORIES = ['NOISE', 'CURFEW', 'ALCOHOL', 'SMOKING', 'FIGHT', 'DAMAGE', 'GUEST', 'MISCONDUCT', 'OTHER'] as const;
export const SEVERITIES = ['MINOR', 'MAJOR', 'SEVERE'] as const;
export const ACTIONS = ['NONE', 'WARNING', 'COUNSELLING', 'FINE', 'REPORTED_TO_HR', 'SUSPENSION'] as const;
export const REPEAT_WINDOW_DAYS = 90;
export const REPEAT_AT = 3;

const DAY_MS = 86_400_000;

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

/** How many incidents each employee has had in the last 90 days. */
async function recentCounts(profileIds: string[], now = new Date()) {
  if (profileIds.length === 0) return new Map<string, number>();
  const rows = await db.disciplineIncident.groupBy({
    by: ['studentProfileId'],
    where: { studentProfileId: { in: profileIds }, occurredAt: { gte: new Date(now.getTime() - REPEAT_WINDOW_DAYS * DAY_MS) } },
    _count: { _all: true },
  });
  return new Map(rows.map((r) => [r.studentProfileId, r._count._all]));
}

/** The register's rows: each incident with who recorded it and how often the employee has been here lately. */
async function present<T extends { studentProfileId: string; reportedById: string }>(rows: T[]) {
  const [counts, reporters] = await Promise.all([
    recentCounts([...new Set(rows.map((r) => r.studentProfileId))]),
    db.user.findMany({ where: { id: { in: [...new Set(rows.map((r) => r.reportedById))] } }, select: { id: true, name: true } }),
  ]);
  const names = new Map(reporters.map((u) => [u.id, u.name]));
  return rows.map((r) => {
    const recent = counts.get(r.studentProfileId) ?? 0;
    return { ...r, reportedBy: names.get(r.reportedById) ?? null, recentCount: recent, repeatOffender: recent >= REPEAT_AT };
  });
}

export interface IncidentFilters {
  studentProfileId?: string;
  category?: string;
  status?: 'OPEN' | 'CLOSED';
  from?: Date;
  to?: Date;
  propertyId?: string;
  q?: string;
}

export async function listIncidents(f: IncidentFilters, pagination: Pagination | null) {
  const where: Prisma.DisciplineIncidentWhereInput = {
    ...(f.studentProfileId ? { studentProfileId: f.studentProfileId } : {}),
    ...(f.category ? { category: f.category } : {}),
    ...(f.status ? { status: f.status } : {}),
    ...(f.propertyId ? { propertyId: f.propertyId } : {}),
    ...(f.from || f.to ? { occurredAt: { ...(f.from ? { gte: f.from } : {}), ...(f.to ? { lte: f.to } : {}) } } : {}),
    ...(f.q
      ? {
          OR: [
            { description: { contains: f.q, mode: 'insensitive' } },
            { student: { user: { name: { contains: f.q, mode: 'insensitive' } } } },
            { student: { employeeCode: { contains: f.q, mode: 'insensitive' } } },
          ],
        }
      : {}),
  };
  const orderBy = { occurredAt: 'desc' as const };
  if (!pagination) return present(await db.disciplineIncident.findMany({ where, include, orderBy, take: 300 }));
  const [items, total] = await Promise.all([db.disciplineIncident.findMany({ where, include, orderBy, skip: pagination.skip, take: pagination.limit }), db.disciplineIncident.count({ where })]);
  return paginated(await present(items), total, pagination);
}

export interface IncidentInput {
  studentProfileId: string;
  occurredAt: Date;
  category: string;
  severity: string;
  description: string;
  witnesses?: string | null;
  action?: string;
  actionNote?: string | null;
}

export async function createIncident(input: IncidentInput, 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');
  if (input.occurredAt.getTime() > Date.now() + 5 * 60_000) throw new BadRequestError('An incident cannot be in the future');
  const tenantId = getTenantIdOrThrow();
  const row = await db.disciplineIncident.create({
    data: { tenantId, ...input, action: input.action ?? 'NONE', propertyId: profile.propertyId, reportedById: actorId },
    include,
  });
  inBackground('push: incident recorded', () => notifyIncidentRecorded(tenantId, row.id));
  return (await present([row]))[0];
}

export async function updateIncident(id: string, input: Partial<Omit<IncidentInput, 'studentProfileId'>> & { status?: 'OPEN' | 'CLOSED' }) {
  const existing = await db.disciplineIncident.findFirst({ where: { id } });
  if (!existing) throw new NotFoundError('Incident not found');
  if (existing.status === 'CLOSED' && input.status !== 'OPEN' && Object.keys(input).some((k) => k !== 'status')) throw new ConflictError('Reopen the incident to change it');
  const row = await db.disciplineIncident.update({
    where: { id },
    data: { ...input, ...(input.status === 'CLOSED' ? { closedAt: new Date() } : input.status === 'OPEN' ? { closedAt: null } : {}) },
    include,
  });
  return (await present([row]))[0];
}

/**
 * One employee's record: every incident, and whether they are a repeat
 * offender now. Staff see who reported it and the witnesses; the employee's
 * own view leaves both out.
 */
export async function historyFor(profileId: string) {
  const rows = await listIncidents({ studentProfileId: profileId }, null);
  const list = Array.isArray(rows) ? rows : rows.items;
  const recent = list[0]?.recentCount ?? 0;
  return { incidents: list, recentCount: recent, repeatOffender: recent >= REPEAT_AT };
}

export async function myIncidents(userId: string) {
  const p = await db.studentProfile.findFirst({ where: { userId }, select: { id: true } });
  if (!p) throw new NotFoundError('No employee record for this account');
  const rows = await db.disciplineIncident.findMany({
    where: { studentProfileId: p.id },
    orderBy: { occurredAt: 'desc' },
    take: 100,
    select: { id: true, occurredAt: true, category: true, severity: true, description: true, action: true, actionNote: true, status: true },
  });
  return rows;
}

/** Counts for the register's header and the report: by category, severity and action, and the repeat offenders. */
export async function summary(from: Date, to: Date, propertyId?: string) {
  const where = { occurredAt: { gte: from, lte: to }, ...(propertyId ? { propertyId } : {}) };
  const [byCategory, bySeverity, byAction, open] = await Promise.all([
    db.disciplineIncident.groupBy({ by: ['category'], where, _count: { _all: true } }),
    db.disciplineIncident.groupBy({ by: ['severity'], where, _count: { _all: true } }),
    db.disciplineIncident.groupBy({ by: ['action'], where, _count: { _all: true } }),
    db.disciplineIncident.count({ where: { ...where, status: 'OPEN' } }),
  ]);
  const windowStart = new Date(Date.now() - REPEAT_WINDOW_DAYS * DAY_MS);
  const repeat = await db.disciplineIncident.groupBy({
    by: ['studentProfileId'],
    where: { occurredAt: { gte: windowStart }, ...(propertyId ? { propertyId } : {}) },
    _count: { _all: true },
    having: { studentProfileId: { _count: { gte: REPEAT_AT } } },
  });
  const people = await db.studentProfile.findMany({
    where: { id: { in: repeat.map((r) => r.studentProfileId) } },
    select: { id: true, employeeCode: true, user: { select: { name: true } }, department: { select: { name: true } } },
  });
  const count = new Map(repeat.map((r) => [r.studentProfileId, r._count._all]));
  const tally = (rows: { _count: { _all: number } }[], key: (r: never) => string) => Object.fromEntries(rows.map((r) => [key(r as never), r._count._all]));
  return {
    from,
    to,
    total: byCategory.reduce((n, r) => n + r._count._all, 0),
    open,
    byCategory: tally(byCategory, (r: { category: string }) => r.category),
    bySeverity: tally(bySeverity, (r: { severity: string }) => r.severity),
    byAction: tally(byAction, (r: { action: string }) => r.action),
    repeatOffenders: people
      .map((p) => ({ studentProfileId: p.id, name: p.user.name, employeeCode: p.employeeCode, department: p.department?.name ?? null, incidents: count.get(p.id) ?? 0 }))
      .sort((a, b) => b.incidents - a.incidents),
  };
}
