import { Role, StudentRequestStatus, StudentRequestType, TenantKind } from '@prisma/client';
import { hasFeature } from '../../lib/tenant-features';
import { db, prismaUnscoped } from '../../lib/prisma';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';
import { tenantHasFeature } from '../../middleware/requireFeature';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { inBackground, notifyRequestEscalated } from '../notifications/notifications.service';

/**
 * The grievance desk (Sprint 2, TEPL), on top of requests: a sub-category for
 * complaints and repairs, escalation when a request runs past its target,
 * the employee's rating once it is closed, and the numbers HR asks for.
 */

export const REQUEST_CATEGORIES: Partial<Record<StudentRequestType, readonly string[]>> = {
  COMPLAINT: ['FOOD', 'CLEANLINESS', 'ROOM', 'WATER_POWER', 'SAFETY', 'STAFF_BEHAVIOUR', 'HARASSMENT', 'FACILITIES', 'OTHER'],
  MAINTENANCE: ['ELECTRICAL', 'PLUMBING', 'CARPENTRY', 'FURNITURE', 'CIVIL', 'APPLIANCE', 'OTHER'],
};

/** A category is checked against the request's type, and only where the desk is on. */
export async function checkCategory(type: StudentRequestType, category: string | undefined) {
  if (!category) return undefined;
  if (!(await tenantHasFeature(getTenantIdOrThrow(), 'grievanceDesk'))) throw new BadRequestError('Categories are not available here');
  const allowed = REQUEST_CATEGORIES[type];
  if (!allowed || !allowed.includes(category)) throw new BadRequestError('Choose a category from the list');
  return category;
}

const CLOSED: StudentRequestStatus[] = [StudentRequestStatus.RESOLVED, StudentRequestStatus.APPROVED, StudentRequestStatus.REJECTED];

/** The employee rates how their request was handled, once it is closed. They may change it within a week. */
export async function rateRequest(userId: string, id: string, rating: number, comment: string | null) {
  if (!(await tenantHasFeature(getTenantIdOrThrow(), 'grievanceDesk'))) throw new BadRequestError('Ratings are not available here');
  const r = await db.studentRequest.findFirst({ where: { id, student: { userId } }, select: { id: true, status: true, resolvedAt: true, ratedAt: true } });
  if (!r) throw new NotFoundError('Request not found');
  if (!CLOSED.includes(r.status)) throw new ConflictError('You can rate it once it is closed');
  if (r.ratedAt && Date.now() - r.ratedAt.getTime() > 7 * 86_400_000) throw new ConflictError('The rating can be changed for a week');
  await db.studentRequest.update({ where: { id }, data: { rating, ratingComment: comment, ratedAt: new Date() } });
  return { rating, ratingComment: comment };
}

/**
 * The hourly pass: a complaint or repair still open past its target is
 * escalated — to the hostel's managers at once (level 1), and again a day
 * later (level 2). Each level is claimed before anyone is told, so a level
 * goes out once however many servers tick.
 */
export async function runEscalations(now = new Date()): Promise<void> {
  // Only tenants with the desk, so overdue requests elsewhere cannot fill the batch.
  const kinds = Object.values(TenantKind).filter((k) => hasFeature(k, 'grievanceDesk'));
  const due = await prismaUnscoped.studentRequest.findMany({
    where: {
      tenant: { kind: { in: kinds } },
      status: { in: [StudentRequestStatus.OPEN, StudentRequestStatus.IN_PROGRESS] },
      type: { in: [StudentRequestType.COMPLAINT, StudentRequestType.MAINTENANCE, StudentRequestType.OTHER] },
      escalationLevel: { lt: 2 },
      dueBy: { lt: now },
    },
    select: { id: true, tenantId: true, dueBy: true, escalationLevel: true },
    orderBy: { dueBy: 'asc' },
    take: 1000,
  });
  for (const r of due) {
    if (!(await tenantHasFeature(r.tenantId, 'grievanceDesk'))) continue;
    const next = r.escalationLevel + 1;
    // Level 2 waits a full day past the target.
    if (next === 2 && r.dueBy!.getTime() + 86_400_000 > now.getTime()) continue;
    const claimed = await prismaUnscoped.studentRequest.updateMany({ where: { id: r.id, escalationLevel: r.escalationLevel }, data: { escalationLevel: next, escalatedAt: now } });
    if (claimed.count) inBackground('push: request escalated', () => notifyRequestEscalated(r.tenantId, r.id, next));
  }
}

/** HR's view of the last N days: by category, how fast, how many escalated, how they were rated. */
export async function grievanceSummary(days: number, propertyId?: string) {
  const since = new Date(Date.now() - days * 86_400_000);
  const rows = await db.studentRequest.findMany({
    where: { type: { in: [StudentRequestType.COMPLAINT, StudentRequestType.MAINTENANCE] }, createdAt: { gte: since }, status: { not: StudentRequestStatus.CANCELLED }, ...(propertyId ? { student: { propertyId } } : {}) },
    select: { type: true, category: true, status: true, createdAt: true, resolvedAt: true, dueBy: true, escalationLevel: true, rating: true, anonymous: true },
    take: 10000,
  });
  const groups = new Map<string, typeof rows>();
  for (const r of rows) {
    const key = `${r.type}:${r.category ?? 'UNSORTED'}`;
    groups.set(key, [...(groups.get(key) ?? []), r]);
  }
  const stats = (list: typeof rows) => {
    const closed = list.filter((r) => r.resolvedAt);
    const hours = closed.map((r) => (r.resolvedAt!.getTime() - r.createdAt.getTime()) / 3_600_000);
    const withTarget = closed.filter((r) => r.dueBy);
    const rated = list.filter((r) => r.rating != null);
    return {
      raised: list.length,
      closed: closed.length,
      open: list.length - closed.length,
      avgHoursToClose: hours.length ? Math.round((hours.reduce((a, b) => a + b, 0) / hours.length) * 10) / 10 : null,
      withinTarget: withTarget.length ? Math.round((withTarget.filter((r) => r.resolvedAt! <= r.dueBy!).length / withTarget.length) * 100) : null,
      escalated: list.filter((r) => r.escalationLevel > 0).length,
      anonymous: list.filter((r) => r.anonymous).length,
      avgRating: rated.length ? Math.round((rated.reduce((a, r) => a + r.rating!, 0) / rated.length) * 10) / 10 : null,
      ratings: rated.length,
    };
  };
  return {
    days,
    overall: stats(rows),
    byCategory: [...groups.entries()]
      .map(([key, list]) => ({ type: key.split(':')[0] as StudentRequestType, category: key.split(':')[1], ...stats(list) }))
      .sort((a, b) => b.raised - a.raised),
  };
}

/** Staff the escalation goes to: the managers (MANAGE_STAFF), and the assignee if any. */
export function escalationAudience(role: Role) {
  return role === Role.HOSTEL_ADMIN;
}
