import { createHmac } from 'node:crypto';
import { Prisma, StudentRequestStatus } from '@prisma/client';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { ConflictError, NotFoundError } from '../../lib/errors';
import { env } from '../../config/env';

/**
 * Employee feedback (Sprint 2, TEPL): once a month, 1–5 ratings for each part
 * of hostel life and a comment, anonymously if they wish. HR reads the
 * averages month by month, the comments, the words that keep coming up, and
 * how closed requests were rated.
 *
 * Anonymous feedback keeps no link to the person. One-a-month is enforced by
 * `submitterKey`, an HMAC of the employee and the month under a server
 * secret, which cannot be turned back into a name.
 */

export const AREAS = ['FOOD', 'CLEANLINESS', 'ROOM', 'WATER_POWER', 'SECURITY', 'STAFF', 'WIFI'] as const;
export type Area = (typeof AREAS)[number];

const IST_MS = 330 * 60_000;
const monthOf = (d = new Date()) => new Date(d.getTime() + IST_MS).toISOString().slice(0, 7);
const keyFor = (profileId: string, period: string) => createHmac('sha256', env.JWT_REFRESH_SECRET).update(`feedback:${profileId}:${period}`).digest('hex');

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

/** Whether they have given this month's feedback yet. */
export async function myStatus(userId: string) {
  const p = await profileOf(userId);
  const period = monthOf();
  const done = await db.feedback.findFirst({ where: { submitterKey: keyFor(p.id, period) }, select: { createdAt: true } });
  return { period, submitted: !!done, submittedAt: done?.createdAt ?? null, areas: AREAS };
}

export async function submit(userId: string, input: { ratings: Partial<Record<Area, number>>; overall?: number | null; comment?: string | null; anonymous: boolean }) {
  const p = await profileOf(userId);
  const period = monthOf();
  try {
    await db.feedback.create({
      data: {
        tenantId: getTenantIdOrThrow(),
        propertyId: p.propertyId,
        studentProfileId: input.anonymous ? null : p.id,
        anonymous: input.anonymous,
        submitterKey: keyFor(p.id, period),
        period,
        ratings: input.ratings as Prisma.InputJsonValue,
        overall: input.overall ?? null,
        comment: input.comment?.trim() || null,
      },
    });
  } catch (e) {
    if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') throw new ConflictError('You have already given feedback this month — thank you');
    throw e;
  }
  return myStatus(userId);
}

const STOP = new Set('the a an and or but of to in on at for with is are was were be been it this that these those i we you they he she my our your their me us them not no very so too also just from by as if then than there here have has had do does did can could will would should about into over more most some any all its am our'.split(' '));

/** The words that keep coming up in comments, for a quick read of the themes. */
function themes(comments: string[], top = 15) {
  const counts = new Map<string, number>();
  for (const c of comments) {
    const seen = new Set<string>();
    for (const w of c.toLowerCase().match(/[a-z][a-z-]{2,}/g) ?? []) {
      if (STOP.has(w) || seen.has(w)) continue;
      seen.add(w);
      counts.set(w, (counts.get(w) ?? 0) + 1);
    }
  }
  return [...counts.entries()].filter(([, n]) => n > 1).sort((a, b) => b[1] - a[1]).slice(0, top).map(([word, count]) => ({ word, count }));
}

/** HR's view over the last N months: averages by area and month, responses, comments, themes, request ratings. */
export async function summary(months: number, propertyId?: string) {
  // Months are India-time months, as responses are filed (monthOf).
  const now = new Date(Date.now() + IST_MS);
  const periods: string[] = [];
  for (let i = months - 1; i >= 0; i--) {
    const d = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - i, 15));
    periods.push(d.toISOString().slice(0, 7));
  }
  const rows = await db.feedback.findMany({
    where: { period: { in: periods }, ...(propertyId ? { propertyId } : {}) },
    select: { period: true, ratings: true, overall: true, comment: true, anonymous: true, createdAt: true, studentProfileId: true },
    orderBy: { createdAt: 'desc' },
    take: 20000,
  });
  const byMonth = periods.map((period) => {
    const list = rows.filter((r) => r.period === period);
    const avg = (vals: number[]) => (vals.length ? Math.round((vals.reduce((a, b) => a + b, 0) / vals.length) * 10) / 10 : null);
    const areas = Object.fromEntries(AREAS.map((a) => [a, avg(list.map((r) => (r.ratings as Record<string, number>)[a]).filter((v): v is number => typeof v === 'number'))]));
    return { period, responses: list.length, overall: avg(list.map((r) => r.overall).filter((v): v is number => typeof v === 'number')), areas };
  });
  const names = new Map((await db.studentProfile.findMany({ where: { id: { in: rows.filter((r) => r.studentProfileId).map((r) => r.studentProfileId!) } }, select: { id: true, user: { select: { name: true } } } })).map((p) => [p.id, p.user.name]));
  const comments = rows
    .filter((r) => r.comment)
    .slice(0, 100)
    .map((r) => {
      // Sprint 7 hardening: an anonymous comment carries only its month — an exact time could point to who wrote it.
      const hidden = r.anonymous || !r.studentProfileId;
      return { period: r.period, comment: r.comment!, overall: r.overall, at: hidden ? null : r.createdAt, from: hidden ? null : names.get(r.studentProfileId!) ?? null };
    });
  const since = new Date(Date.UTC(Number(periods[0].slice(0, 4)), Number(periods[0].slice(5, 7)) - 1, 1));
  const rated = await db.studentRequest.aggregate({
    where: { rating: { not: null }, ratedAt: { gte: since }, status: { not: StudentRequestStatus.CANCELLED }, ...(propertyId ? { student: { propertyId } } : {}) },
    _avg: { rating: true },
    _count: { rating: true },
  });
  return {
    months: byMonth,
    comments,
    themes: themes(rows.map((r) => r.comment ?? '').filter(Boolean)),
    requestRatings: { average: rated._avg.rating ? Math.round(rated._avg.rating * 10) / 10 : null, count: rated._count.rating },
  };
}
