import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { createHash } from "node:crypto";
import type { Readable } from "node:stream";
import { z, type ZodTypeAny } from "zod";
import { execute, one, pool, type Row } from "../db/db.js";
import { DomainError } from "./errors.js";

export interface Access { membershipId: string; roleCode: string; roleLabel: string; permissions: ReadonlySet<string>; providerId: string | null; providerName: string | null; siteIds: string[]; classIds: string[] }
export interface User { id: string; name: string; email: string; mustChangePassword: boolean; twoFactorMethod: "none" | "email" | "totp"; sessionId: string }
/** Everything a handler needs. `pid` and `access` exist only on /projects/:p routes. */
export interface Ctx { req: FastifyRequest; reply: FastifyReply; user: User; access: Access; pid: string; params: Record<string, string>; query: Record<string, string | undefined>; body: unknown; ip: string }
export interface Options { perm?: string | readonly string[]; v1?: readonly string[]; public?: boolean; limit?: number; allowPasswordChange?: boolean }
type Method = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";

export interface AuthPort { user(req: FastifyRequest): Promise<User | null>; access(userId: string, projectId: string): Promise<Access | null> }
let auth: AuthPort;
export const setAuthPort = (port: AuthPort) => { auth = port; };

export const deny = (): never => { throw new DomainError(403, "FORBIDDEN", "You do not have access to this."); };
export const notFound = (what: string): never => { throw new DomainError(404, "NOT_FOUND", `${what} was not found.`); };
export const invalid = (path: string, message: string, code = "INVALID"): never => { throw new DomainError(422, "VALIDATION", "Some fields need attention.", [{ path, code, message }]); };
export const conflict = (code: string, message: string): never => { throw new DomainError(409, code, message); };
export const can = (c: Ctx, perm: string) => c.access.permissions.has(perm);
export const parse = <S extends ZodTypeAny>(schema: S, body: unknown): z.output<S> => schema.parse(body ?? {}) as z.output<S>;
export const id = z.coerce.string().regex(/^\d{1,19}$/);

/** The WHERE condition that keeps a provider user inside their own provider, sites and classes. Put it in every scoped query. */
export function scope(c: Ctx, cols: { provider: string; cls?: string; site?: string }): { sql: string; args: (string | string[])[] } {
  const parts: string[] = [], args: (string | string[])[] = [];
  if (c.access.providerId) { parts.push(`${cols.provider}=?`); args.push(c.access.providerId); }
  const limited = c.access.siteIds.length + c.access.classIds.length > 0;
  if (limited && cols.cls) {
    const or: string[] = [];
    if (c.access.classIds.length) { or.push(`${cols.cls} IN (?)`); args.push(c.access.classIds); }
    if (c.access.siteIds.length) { or.push(cols.site ? `${cols.site} IN (?)` : `${cols.cls} IN (SELECT id FROM training_classes WHERE site_id IN (?))`); args.push(c.access.siteIds); }
    parts.push(`(${or.join(" OR ")})`);
  }
  return { sql: parts.length ? parts.join(" AND ") : "1=1", args };
}
/** Loads a class only if the caller may see it. */
export async function classInScope(c: Ctx, classId: string): Promise<Row> {
  const s = scope(c, { provider: "c.provider_id", cls: "c.id", site: "c.site_id" });
  return (await one(pool, `SELECT c.* FROM training_classes c WHERE c.id=? AND c.project_id=? AND ${s.sql}`, [classId, c.pid, ...s.args] as never[])) ?? notFound("Class");
}
export function sameProvider(c: Ctx, providerId: string | null | undefined): void { if (c.access.providerId && c.access.providerId !== String(providerId)) notFound("Record"); }

export interface Paging { page: number; pageSize: number; offset: number }
export function paging(q: Record<string, string | undefined>): Paging {
  const int = (v: string | undefined, d: number, max: number) => { const n = Number(v); return Number.isInteger(n) && n > 0 ? Math.min(n, max) : d; };
  const page = int(q["page"], 1, 1_000_000), pageSize = int(q["pageSize"], 25, 200);
  return { page, pageSize, offset: (page - 1) * pageSize };
}
export const like = (s: string) => `%${s.replace(/[\\%_]/g, "\\$&")}%`;

const isMutation = (m: string) => m !== "GET" && m !== "HEAD";
export function route(app: FastifyInstance, method: Method, url: string, o: Options, handler: (c: Ctx) => Promise<unknown>): void {
  app.route({
    method, url, config: { ...(o.v1 ? { v1: o.v1 } : {}), rateLimit: { max: o.limit ?? 600, timeWindow: "1 minute" } },
    handler: async (req, reply) => {
      const user = await auth.user(req);
      const params = req.params as Record<string, string>;
      for (const [k, v] of Object.entries(params)) if (["p", "id", "siteId", "row", "file"].includes(k) && !/^\d{1,19}$/.test(v)) notFound("Page");
      const c: Ctx = { req, reply, user: user as User, access: undefined as unknown as Access, pid: params["p"] ?? "", params, query: req.query as Ctx["query"], body: req.body, ip: req.ip };
      if (!o.public) {
        if (!user) throw new DomainError(401, "UNAUTHENTICATED", "Sign in to continue.");
        if (isMutation(method) && (req.headers["x-csrf-token"] ?? "") !== (req.cookies["pbps_csrf"] ?? "-")) throw new DomainError(403, "CSRF", "Your session could not be confirmed. Reload the page and try again.");
        if (user.mustChangePassword && !o.allowPasswordChange) throw new DomainError(403, "PASSWORD_CHANGE_REQUIRED", "Choose a new password before you continue.");
        if (c.pid) {
          const access = await auth.access(user.id, c.pid);
          if (!access) deny();
          c.access = access!;
        }
        const need = typeof o.perm === "string" ? [o.perm] : o.perm ?? [];
        if (need.length) {
          if (!c.access) c.access = (await auth.access(user.id, "*")) ?? deny();
          if (!need.some((k) => c.access.permissions.has(k))) deny();
        }
      }
      const key = req.headers["idempotency-key"];
      if (typeof key !== "string" || !user || !isMutation(method)) return send(reply, await handler(c));
      const idem = createHash("sha256").update(`${user.id}:${method}:${req.url}:${key}`).digest("hex");
      const old = await one(pool, "SELECT response_body AS b FROM idempotency_keys WHERE idem_key=?", [idem]);
      if (old) return send(reply, JSON.parse(old["b"] as string));
      const result = await handler(c);
      await execute(pool, "INSERT IGNORE INTO idempotency_keys (idem_key, user_id, route, response_code, response_body) VALUES (?,?,?,?,?)", [idem, user.id, `${method} ${url}`.slice(0, 100), 200, JSON.stringify(result ?? null)]);
      return send(reply, result);
    },
  });
}
function send(reply: FastifyReply, result: unknown) {
  if (reply.sent) return reply;
  return result === undefined ? reply.code(204).send() : reply.send(result);
}
export function sendFile(c: Ctx, name: string, type: string, body: Buffer | string | Readable, size?: number): FastifyReply {
  if (size !== undefined) c.reply.header("content-length", size);
  return c.reply.header("content-type", type).header("x-content-type-options", "nosniff").header("content-disposition", `attachment; filename="${name.replace(/[^\w.-]+/g, "_")}"; filename*=UTF-8''${encodeURIComponent(name.replace(/[\ud800-\udfff]/g, "_")).replace(/['()*]/g, (x) => `%${x.charCodeAt(0).toString(16)}`)}`).send(body);
}
export interface Upload { fields: Record<string, string>; files: { field: string; name: string; type: string; data: Buffer }[] }
export async function readUpload(c: Ctx): Promise<Upload> {
  const out: Upload = { fields: {}, files: [] };
  if (!c.req.isMultipart()) throw new DomainError(415, "FILE_EXPECTED", "Send a file.");
  for await (const part of c.req.parts()) {
    if (part.type === "file") { const data = await part.toBuffer(); if (part.filename) out.files.push({ field: part.fieldname, name: part.filename, type: part.mimetype, data }); }
    else out.fields[part.fieldname] = String(part.value);
  }
  return out;
}
