import { env } from "../../config/env.js";
import { audit } from "../../core/audit/audit.js";
import { randomToken, sha256 } from "../../core/crypto.js";
import { execute, insert, one, pool, query, transaction, type Db, type Row } from "../../core/db/db.js";
import { DomainError } from "../../core/http/errors.js";
import { can, conflict, deny, invalid, like, notFound, paging, scope, type Ctx } from "../../core/http/route.js";
import { queueMail } from "../../core/mail/mail.js";
import { addDays, today } from "../../shared/dates.js";
import { parsePhone } from "../../shared/phone.js";
import { notifyRoles } from "../notifications/index.js";
import { queueKpis } from "../projects/index.js";

const iso = (d: Date) => d.toISOString().slice(0, 23).replace("T", " ");
const SEL = "SELECT g.*, p.name AS pname, p.code AS pcode, p.reply_to_email AS preply, u.name AS aname FROM grievance_cases g JOIN providers p ON p.id=g.provider_id LEFT JOIN users u ON u.id=g.assigned_to";
/** Providers answer the case without learning who sent it (V1 rule). It is hidden here, so no page or export can show it. */
const hidden = (c: Ctx) => Boolean(c.access?.providerId);
const CONFIDENTIAL = { submitterName: "Confidential", submitterEmail: "", submitterPhone: undefined, region: undefined };
const shown = (c: Ctx, v: ReturnType<typeof view>) => (hidden(c) ? { ...v, ...CONFIDENTIAL, messages: v.messages.map((m) => (m.kind === "submitter" ? { ...m, author: "Submitter" } : m)) } : v);
const view = (g: Row, messages: Row[] = []) => ({ id: g["id"], ref: g["ref"], providerId: g["provider_id"], providerName: g["pname"], category: g["category"], subject: g["subject"], status: g["status"], priority: g["priority"], submittedAt: g["submitted_at"], dueAt: g["due_at"], firstResponseAt: g["first_response_at"] ?? undefined, resolvedAt: g["resolved_at"] ?? undefined, overdue: !g["first_response_at"] && Date.parse(g["due_at"]) < Date.now(), satisfaction: g["satisfaction_score"] ?? undefined, satisfactionComment: g["satisfaction_comment"] ?? undefined, assignedTo: g["aname"] ?? undefined, submitterName: g["submitter_name"], submitterEmail: g["submitter_email"], submitterPhone: g["submitter_phone"] ?? undefined, region: g["region"] ?? undefined, description: g["description"], replyTo: g["preply"] ?? undefined,
  messages: messages.map((m) => ({ id: m["id"], at: m["created_at"], author: m["author_name"], kind: m["author_type"] === "public" ? "submitter" : m["visibility"] === "internal" ? "internal_note" : "public_reply", body: m["body"] })) });
/** Plain text only; links and markup in the public form are refused rather than cleaned (V1 security rule). */
function plain(s: string, path: string, max: number): string {
  const t = s.normalize("NFC").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f‪-‮⁦-⁩]/g, "").trim();
  if (!t) invalid(path, "This is required.");
  if (t.length > max) invalid(path, `Use at most ${max} characters.`);
  if (/<[a-z!/]|javascript:|&#/i.test(t)) invalid(path, "Use plain text only.");
  return t;
}
export interface PublicInput { providerId: string; category: string; subject: string; description: string; region?: string | undefined; name: string; email: string; phone?: string | undefined }
async function open(tx: Db, pid: string, b: PublicInput, channel: string): Promise<Row> {
  const p = (await one(tx, "SELECT p.*, pr.grievance_sla_days AS sla FROM providers p JOIN projects pr ON pr.id=p.project_id WHERE p.id=? AND p.project_id=? AND p.status<>'onboarding'", [b.providerId, pid])) ?? invalid("providerId", "Choose the training provider."), phone = b.phone ? parsePhone(b.phone) : null;
  if (phone && !phone.ok) invalid("phone", phone.message);
  const year = today().slice(0, 4);
  await execute(tx, "INSERT IGNORE INTO id_sequences (scope, next_value) VALUES (?,1)", [`grm:${year}`]);
  let n = Number((await one(tx, "SELECT next_value AS v FROM id_sequences WHERE scope=? FOR UPDATE", [`grm:${year}`]))!["v"]);
  while (await one(tx, "SELECT 1 AS x FROM grievance_cases WHERE ref=?", [`GRM-${year}-${String(n).padStart(6, "0")}`])) n++;
  await execute(tx, "UPDATE id_sequences SET next_value=? WHERE scope=?", [n + 1, `grm:${year}`]);
  const now = new Date(), due = new Date(now.getTime() + p["sla"] * 86_400_000), ref = `GRM-${year}-${String(n).padStart(6, "0")}`, subject = plain(b.subject, "subject", 190), description = plain(b.description, "description", 5000), email = b.email.trim().toLowerCase();
  const gid = await insert(tx, "grievance_cases", { project_id: pid, provider_id: b.providerId, ref, category: b.category, channel, subject, description, submitter_name: plain(b.name, "name", 120), submitter_email: email, submitter_phone: phone?.ok ? phone.e164 : undefined, region: b.region, status: "new", submitted_at: iso(now), due_at: iso(due) });
  await insert(tx, "grievance_messages", { case_id: gid, author_type: "public", author_name: b.name.trim(), body: description, visibility: "public" });
  await queueMail(tx, { projectId: pid, to: email, subject: `We received your message (${ref})`, text: `Thank you. Your reference is ${ref}.\nWe will answer by ${iso(due).slice(0, 10)}.\nYou can follow it here:\n${env.APP_URL}/feedback/status`, template: "grievance.received", replyTo: p["reply_to_email"], entityType: "grievance", entityId: gid });
  if (p["notification_email"]) await queueMail(tx, { projectId: pid, to: p["notification_email"], subject: `New ${b.category}: ${ref}`, text: `A new case was submitted about ${p["name"]}.\nAnswer it by ${iso(due).slice(0, 10)}.\n${env.APP_URL}/p/${pid}/grievances/${gid}`, template: "grievance.new_case", entityType: "grievance", entityId: gid });
  await notifyRoles(tx, pid, { providerId: b.providerId, roles: ["tp_admin", "tp_site_lead"], type: "grievance.new_case", severity: "warning", title: `New ${b.category}: ${subject}`, link: `/p/${pid}/grievances/${gid}`, dedupe: `grv-new:${gid}` });
  await queueKpis(tx, pid);
  return { id: gid, ref, dueAt: due.toISOString() };
}
export const submitPublic = async (c: Ctx, b: PublicInput) => { const r = await transaction((tx) => open(tx, c.pid, b, "web")); return { ref: r["ref"], dueAt: r["dueAt"] }; };
export async function createInternal(c: Ctx, b: PublicInput & { channel: string }) {
  const r = await transaction(async (tx) => { if (c.access.providerId && c.access.providerId !== b.providerId) deny(); const x = await open(tx, c.pid, b, b.channel); await audit(tx, c, { module: "grievance", action: "recorded", entityType: "grievance", entityId: x["id"], providerId: b.providerId, summary: `Case ${x["ref"]} recorded (${b.channel})` }); return x; });
  return get(c, r["id"]);
}
export const publicProviders = (pid: string) => query(pool, "SELECT id, name FROM providers WHERE project_id=? AND status IN ('active','suspended') ORDER BY name", [pid]);
export const publicProjects = () => query(pool, "SELECT id, title FROM projects ORDER BY id");
export const publicLocations = () => query(pool, "SELECT id, code, name FROM locations WHERE is_active=1 ORDER BY name");
/** The same answer for a wrong reference and a wrong email, so references cannot be probed. */
export async function lookup(ref: string, email: string) {
  const g = await one(pool, `${SEL} WHERE g.ref=? AND g.submitter_email=?`, [ref.trim().toUpperCase(), email.trim().toLowerCase()]);
  if (!g) throw new DomainError(404, "NOT_FOUND", "No case matches this reference and email.");
  const m = await query(pool, "SELECT * FROM grievance_messages WHERE case_id=? AND visibility='public' ORDER BY id", [g["id"]]);
  return { ref: g["ref"], status: g["status"], submittedAt: g["submitted_at"], dueAt: g["due_at"], subject: g["subject"], providerName: g["pname"], replies: view(g, m.filter((x) => x["author_type"] !== "public")).messages, canRate: ["resolved", "closed"].includes(g["status"]) && g["satisfaction_score"] === null && Boolean(g["satisfaction_token_hash"]) };
}
export async function rateCase(ref: string, token: string, score: number, comment?: string) {
  const r = await execute(pool, "UPDATE grievance_cases SET satisfaction_score=?, satisfaction_comment=? WHERE ref=? AND satisfaction_token_hash=? AND satisfaction_score IS NULL", [score, comment ? plain(comment, "comment", 1000) : null, ref, sha256(token)]);
  if (!r.affectedRows) throw new DomainError(410, "LINK_EXPIRED", "This link is not valid or was already used.");
  return { ok: true };
}
const S = (c: Ctx) => scope(c, { provider: "g.provider_id" });
const row = async (c: Ctx, gid: string, db: Db = pool): Promise<Row> => { const s = S(c); return (await one(db, `${SEL} WHERE g.id=? AND g.project_id=? AND ${s.sql}`, [gid, c.pid, ...s.args] as never[])) ?? notFound("Case"); };
export async function get(c: Ctx, gid: string) { const g = await row(c, gid); return { ...shown(c, view(g, await query(pool, "SELECT * FROM grievance_messages WHERE case_id=? ORDER BY id", [gid]))), actions: await query(pool, "SELECT id, description, owner_name AS owner, due_date AS dueDate, status FROM grievance_actions WHERE case_id=? ORDER BY id", [gid]) }; }
export async function list(c: Ctx) {
  const q = c.query, s = S(c), pg = paging(q), where = ["g.project_id=?", s.sql], args: unknown[] = [c.pid, ...s.args];
  for (const [k, col] of [["status", "g.status"], ["category", "g.category"], ["providerId", "g.provider_id"]] as const) if (q[k]) { where.push(`${col}=?`); args.push(q[k]); }
  if (q["overdue"] === "true") where.push("g.first_response_at IS NULL AND g.due_at<UTC_TIMESTAMP(3)");
  if (q["q"]) { where.push(hidden(c) ? "(g.ref LIKE ? OR g.subject LIKE ?)" : "(g.ref LIKE ? OR g.subject LIKE ? OR g.submitter_name LIKE ?)"); args.push(like(q["q"]), like(q["q"]), ...(hidden(c) ? [] : [like(q["q"])])); }
  const w = where.join(" AND "), sort = q["sort"]?.startsWith("dueAt") ? "g.due_at" : "g.submitted_at DESC";
  return { items: (await query(pool, `${SEL} WHERE ${w} ORDER BY ${sort}, g.id LIMIT ? OFFSET ?`, [...args, pg.pageSize, pg.offset] as never[])).map((g) => shown(c, view(g))), page: pg.page, pageSize: pg.pageSize, total: (await one(pool, `SELECT COUNT(*) AS n FROM grievance_cases g WHERE ${w}`, args as never[]))!["n"] };
}
export async function stats(c: Ctx) {
  const s = S(c), r = (await one(pool, `SELECT SUM(g.first_response_at IS NULL AND g.status NOT IN ('resolved','closed')) AS o, SUM(g.first_response_at IS NULL AND g.due_at BETWEEN UTC_TIMESTAMP(3) AND UTC_TIMESTAMP(3)+INTERVAL 2 DAY) AS s, SUM(g.first_response_at IS NULL AND g.due_at<UTC_TIMESTAMP(3)) AS v, SUM(g.status='escalated') AS e, SUM(g.first_response_at IS NOT NULL AND g.first_response_at<=g.due_at) AS t, SUM(g.first_response_at IS NOT NULL OR g.due_at<UTC_TIMESTAMP(3)) AS d, AVG(g.satisfaction_score) AS a FROM grievance_cases g WHERE g.project_id=? AND ${s.sql}`, [c.pid, ...s.args] as never[]))!, n = (x: unknown) => Number(x ?? 0);
  return { open: n(r["o"]), dueSoon: n(r["s"]), overdue: n(r["v"]), escalated: n(r["e"]), sla: n(r["d"]) ? Math.round((n(r["t"]) / n(r["d"])) * 1000) / 10 : 0, satisfaction: Math.round(n(r["a"]) * 10) / 10 };
}
/** A public reply is the answer: it resolves the case in the same step. A case can never be resolved without one. */
export async function reply(c: Ctx, gid: string, body: string, visibility: "public" | "internal") {
  await transaction(async (tx) => {
    const g = await row(c, gid, tx), text = body.trim(), answer = visibility === "public";
    if (answer && !can(c, "grievance.respond") && !can(c, "grievance.manage")) deny();
    if (answer && g["status"] === "closed") conflict("CLOSED", "This case is closed. Reopen it to answer again.");
    const token = answer && g["satisfaction_score"] === null ? randomToken() : null;
    const mail = answer ? await queueMail(tx, { projectId: c.pid, to: g["submitter_email"], subject: `Answer to your message (${g["ref"]})`, text: `${text}\n\nReference: ${g["ref"]}${token ? `\nPlease tell us how we did:\n${env.APP_URL}/feedback/rate?ref=${g["ref"]}&token=${token}` : ""}`, template: "grievance.resolved", replyTo: g["preply"], entityType: "grievance", entityId: gid }) : undefined;
    await insert(tx, "grievance_messages", { case_id: gid, author_type: c.access.providerId ? "tp" : c.access.roleCode === "system_admin" ? "admin" : "me", author_user_id: c.user.id, author_name: c.user.name, body: text, visibility, email_outbox_id: mail });
    if (answer) { await execute(tx, "UPDATE grievance_cases SET first_response_at=COALESCE(first_response_at,UTC_TIMESTAMP(3)), resolved_at=UTC_TIMESTAMP(3), status='resolved', satisfaction_token_hash=COALESCE(?,satisfaction_token_hash) WHERE id=?", [token ? sha256(token) : null, gid]); await queueKpis(tx, c.pid); }
    await audit(tx, c, { module: "grievance", action: answer ? "answered" : "note_added", entityType: "grievance", entityId: gid, providerId: g["provider_id"], summary: `${g["ref"]}: ${answer ? "answered and resolved" : "internal note"}` });
  });
  return get(c, gid);
}
const NEXT: Record<string, string[]> = { new: ["acknowledged", "in_progress", "escalated"], acknowledged: ["in_progress", "escalated"], in_progress: ["escalated"], responded: ["closed", "reopened"], escalated: ["in_progress"], resolved: ["closed", "reopened"], closed: ["reopened"], reopened: ["in_progress", "escalated"] };
export async function setStatus(c: Ctx, gid: string, status: string, note?: string) {
  await transaction(async (tx) => {
    const g = await row(c, gid, tx);
    if (status === "resolved") conflict("NO_REPLY", "Answer the submitter: sending the answer resolves the case.");
    if (!NEXT[g["status"]]?.includes(status)) conflict("NOT_ALLOWED", `A case that is ${g["status"]} cannot become ${status}.`);
    if (["resolved", "closed"].includes(status) && !can(c, "grievance.resolve") && !can(c, "grievance.manage")) deny();
    await execute(tx, "UPDATE grievance_cases SET status=?, resolved_at=IF(?='resolved',UTC_TIMESTAMP(3),IF(?='reopened',NULL,resolved_at)), closed_at=IF(?='closed',UTC_TIMESTAMP(3),closed_at), escalated_at=IF(?='escalated',UTC_TIMESTAMP(3),escalated_at) WHERE id=?", [status, status, status, status, status, gid]);
    if (note?.trim()) await insert(tx, "grievance_messages", { case_id: gid, author_type: c.access.providerId ? "tp" : "me", author_user_id: c.user.id, author_name: c.user.name, body: note.trim(), visibility: "internal" });
    await audit(tx, c, { module: "grievance", action: "status", entityType: "grievance", entityId: gid, providerId: g["provider_id"], summary: `${g["ref"]}: ${g["status"]} to ${status}`, after: { note } });
  });
  return get(c, gid);
}
export async function assignees(c: Ctx, gid: string) { const g = await row(c, gid); return query(pool, "SELECT DISTINCT u.id, u.name, COALESCE(p.code, '') AS provider FROM memberships m JOIN users u ON u.id=m.user_id AND u.status='active' JOIN role_permissions x ON x.role_id=m.role_id AND x.perm_key IN ('grievance.respond','grievance.manage') LEFT JOIN providers p ON p.id=m.provider_id WHERE m.project_id=? AND m.status='active' AND (m.provider_id IS NULL OR m.provider_id=?) ORDER BY u.name", [c.pid, g["provider_id"]]); }
export async function assign(c: Ctx, gid: string, userId: string) { await transaction(async (tx) => { const g = await row(c, gid, tx); if (!(await one(tx, "SELECT 1 AS x FROM memberships WHERE user_id=? AND project_id=? AND status='active' AND (provider_id IS NULL OR provider_id=?)", [userId, c.pid, g["provider_id"]]))) invalid("userId", "Choose an active user."); await execute(tx, "UPDATE grievance_cases SET assigned_to=? WHERE id=?", [userId, gid]); await audit(tx, c, { module: "grievance", action: "assigned", entityType: "grievance", entityId: gid, providerId: g["provider_id"], summary: `${g["ref"]} assigned` }); }); return get(c, gid); }
export async function saveAction(c: Ctx, gid: string, b: { id?: string | undefined; description: string; owner?: string | undefined; dueDate?: string | undefined; status: string }) {
  const g = await row(c, gid);
  await transaction(async (tx) => { if (b.id) await execute(tx, "UPDATE grievance_actions SET description=?, owner_name=?, due_date=?, status=?, completed_at=IF(?='done',UTC_TIMESTAMP(3),NULL) WHERE id=? AND case_id=?", [b.description, b.owner ?? null, b.dueDate ?? null, b.status, b.status, b.id, gid]); else await insert(tx, "grievance_actions", { case_id: gid, description: b.description, owner_name: b.owner, due_date: b.dueDate, status: b.status, created_by: c.user.id }); await audit(tx, c, { module: "grievance", action: "action_saved", entityType: "grievance", entityId: gid, providerId: g["provider_id"], summary: `${g["ref"]}: corrective action saved`, after: b }); });
  return get(c, gid);
}
const STOP = new Set("the and for with that this from have not are was were our your about been their they will can you his her has had but all any out who".split(" "));
export async function insights(c: Ctx) {
  const s = S(c), rows = await query(pool, `${SEL} WHERE g.project_id=? AND ${s.sql}${c.query["providerId"] ? " AND g.provider_id=?" : ""}`, [c.pid, ...s.args, ...(c.query["providerId"] ? [c.query["providerId"]] : [])] as never[]), byMonth = new Map<string, Record<string, number | string>>(), byProvider = new Map<string, { code: string; open: number; total: number }>(), words = new Map<string, number>(), days = [0, 0, 0, 0], sat = [0, 0, 0, 0, 0];
  for (const g of rows) {
    const m = String(g["submitted_at"]).slice(0, 7), r = byMonth.get(m) ?? { month: m, complaint: 0, suggestion: 0, question: 0, appreciation: 0 };
    r[g["category"]] = Number(r[g["category"]]) + 1; byMonth.set(m, r);
    const p = byProvider.get(g["pcode"]) ?? { code: g["pcode"], open: 0, total: 0 }; p.total++; if (!g["first_response_at"] && !["resolved", "closed"].includes(g["status"])) p.open++; byProvider.set(g["pcode"], p);
    if (g["first_response_at"]) { const d = (Date.parse(g["first_response_at"]) - Date.parse(g["submitted_at"])) / 86_400_000; days[d <= 2 ? 0 : d <= 4 ? 1 : d <= 7 ? 2 : 3]!++; }
    if (g["satisfaction_score"]) sat[g["satisfaction_score"] - 1]!++;
    for (const w of new Set(String(g["subject"]).toLowerCase().match(/\p{L}{4,}/gu) ?? [])) if (!STOP.has(w)) words.set(w, (words.get(w) ?? 0) + 1);
  }
  const a = await one(pool, "SELECT COUNT(*) AS n FROM grievance_actions x JOIN grievance_cases g ON g.id=x.case_id WHERE x.status='open' AND g.project_id=? AND (? IS NULL OR g.provider_id=?)", [c.pid, c.access.providerId, c.access.providerId]);
  return { byMonth: [...byMonth.values()].sort((x, y) => (String(x["month"]) < String(y["month"]) ? -1 : 1)).slice(-12), byProvider: [...byProvider.values()], responseDays: ["0–2 days", "3–4 days", "5–7 days", "Over 7 days"].map((label, i) => ({ label, value: days[i]! })), satisfaction: sat.map((count, i) => ({ score: i + 1, count })), topics: [...words].filter(([, n]) => n > 1).sort((x, y) => y[1] - x[1]).slice(0, 15).map(([word, count]) => ({ word, count })), openActions: a!["n"] };
}
void addDays;
