import bcrypt from "bcryptjs";
import type { FastifyReply, FastifyRequest } from "fastify";
import { randomInt, randomUUID } from "node:crypto";
import { env } from "../../config/env.js";
import { audit } from "../../core/audit/audit.js";
import { decrypt, encrypt, keyed, newTotpSecret, randomToken, sameHash, sha256, totpOk } 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 { invalid, type Ctx, type User } from "../../core/http/route.js";
import { queueMail } from "../../core/mail/mail.js";

const COOKIE = "pbps_session", CSRF = "pbps_csrf", HOURS = 12, REMEMBER_DAYS = 14;
const secure = () => env.NODE_ENV === "production";

export async function sessionUser(req: FastifyRequest): Promise<User | null> {
  const token = req.cookies[COOKIE];
  if (!token) return null;
  const s = await one(pool, `SELECT s.id, s.user_id, s.last_used_at, u.name, u.email, u.must_change_password, u.two_factor_method FROM user_sessions s JOIN users u ON u.id=s.user_id
    WHERE s.refresh_token_hash=? AND s.revoked_at IS NULL AND s.expires_at>UTC_TIMESTAMP(3) AND u.status='active'`, [sha256(token)]);
  if (!s) return null;
  if (!s["last_used_at"] || Date.now() - Date.parse(s["last_used_at"]) > 300_000) await execute(pool, "UPDATE user_sessions SET last_used_at=UTC_TIMESTAMP(3) WHERE id=?", [s["id"]]);
  return { id: s["user_id"], name: s["name"], email: s["email"], mustChangePassword: Boolean(s["must_change_password"]), twoFactorMethod: s["two_factor_method"], sessionId: String(s["id"]) };
}
export async function startSession(c: Ctx, userId: string, remember: boolean): Promise<void> {
  const token = randomToken(), seconds = remember ? REMEMBER_DAYS * 86_400 : HOURS * 3600;
  await execute(pool, "INSERT INTO user_sessions (user_id, family_id, refresh_token_hash, ip, user_agent, last_used_at, expires_at) VALUES (?,?,?,?,?,UTC_TIMESTAMP(3),UTC_TIMESTAMP(3)+INTERVAL ? SECOND)", [userId, randomUUID(), sha256(token), c.ip, String(c.req.headers["user-agent"] ?? "").slice(0, 250), seconds]);
  await execute(pool, "UPDATE users SET last_login_at=UTC_TIMESTAMP(3), failed_login_count=0, first_failed_at=NULL, locked_until=NULL WHERE id=?", [userId]);
  const age = remember ? { maxAge: seconds } : {};
  c.reply.setCookie(COOKIE, token, { path: "/", httpOnly: true, secure: secure(), sameSite: "lax", ...age }).setCookie(CSRF, randomToken(), { path: "/", secure: secure(), sameSite: "lax", ...age });
}
export const clearCookies = (reply: FastifyReply) => reply.clearCookie(COOKIE, { path: "/" }).clearCookie(CSRF, { path: "/" });
const DUMMY = bcrypt.hashSync("timing-equaliser", 12);

async function fail(u: Row): Promise<void> {
  // V1 rule: five failures within 15 minutes lock the account for 15 minutes.
  await execute(pool, `UPDATE users SET failed_login_count=IF(first_failed_at>UTC_TIMESTAMP(3)-INTERVAL 15 MINUTE, failed_login_count+1, 1), first_failed_at=IF(first_failed_at>UTC_TIMESTAMP(3)-INTERVAL 15 MINUTE, first_failed_at, UTC_TIMESTAMP(3)), locked_until=IF(failed_login_count>=5, UTC_TIMESTAMP(3)+INTERVAL 15 MINUTE, locked_until) WHERE id=?`, [u["id"]]);
}
const locked = (u: Row) => u["locked_until"] && Date.parse(u["locked_until"]) > Date.now();

async function needs2fa(u: Row): Promise<"none" | "email" | "totp"> {
  if (u["two_factor_method"] !== "none") return u["two_factor_method"];
  const s = await one(pool, "SELECT value_json AS v FROM app_settings WHERE setting_key='security.enforce_2fa'");
  if (s?.["v"] !== "true") return "none";
  const r = await one(pool, "SELECT 1 AS x FROM memberships m JOIN roles r ON r.id=m.role_id JOIN app_settings a ON a.setting_key='security.require_2fa_roles' WHERE m.user_id=? AND m.status='active' AND JSON_CONTAINS(a.value_json, JSON_QUOTE(r.code))", [u["id"]]);
  return r ? "email" : "none";
}
async function sendCode(challengeId: string, u: Row): Promise<void> {
  const code = String(randomInt(1_000_000)).padStart(6, "0");
  await execute(pool, "UPDATE email_otp_challenges SET code_hash=?, attempts=0, expires_at=UTC_TIMESTAMP(3)+INTERVAL 10 MINUTE WHERE id=?", [keyed(`${challengeId}:${code}`), challengeId]);
  await queueMail(pool, { to: u["email"], subject: "Your PBPS MIS sign-in code", text: `Your sign-in code is ${code}.\nIt works for 10 minutes. If you did not try to sign in, change your password.`, template: "auth.otp" });
}
export async function login(c: Ctx, email: string, password: string, remember: boolean) {
  const u = await one(pool, "SELECT * FROM users WHERE email=?", [email.trim().toLowerCase()]);
  const wrong = () => new DomainError(401, "INVALID_CREDENTIALS", "The email or password is not correct.");
  if (u && locked(u)) throw new DomainError(429, "ACCOUNT_LOCKED", "Too many failed attempts. Try again in 15 minutes.");
  const ok = await bcrypt.compare(password, u?.["password_hash"] ?? DUMMY);
  if (!u || !ok || u["status"] !== "active") { if (u) await fail(u); throw wrong(); }
  const method = await needs2fa(u);
  if (method === "none") { await startSession(c, u["id"], remember); return { status: u["must_change_password"] ? "password_change_required" : "ok" }; }
  const challengeId = randomUUID();
  await execute(pool, "INSERT INTO email_otp_challenges (id, user_id, code_hash, remember, expires_at) VALUES (?,?,'',?,UTC_TIMESTAMP(3)+INTERVAL 10 MINUTE)", [challengeId, u["id"], remember]);
  if (method === "email") await sendCode(challengeId, u);
  return { status: "2fa_required", challengeId };
}
const challenge = (cid: string) => one(pool, "SELECT c.id AS cid, c.code_hash, c.attempts, c.remember, u.* FROM email_otp_challenges c JOIN users u ON u.id=c.user_id WHERE c.id=? AND c.used_at IS NULL AND c.expires_at>UTC_TIMESTAMP(3) AND u.status='active'", [cid]);
export async function verify2fa(c: Ctx, challengeId: string, code: string) {
  // The attempt is counted before the code is checked, so parallel guesses cannot exceed the limit.
  const counted = await execute(pool, "UPDATE email_otp_challenges SET attempts=attempts+1 WHERE id=? AND used_at IS NULL AND attempts<5", [challengeId]);
  const u = counted.affectedRows ? await challenge(challengeId) : undefined;
  if (!u) throw new DomainError(410, "CHALLENGE_EXPIRED", "This code has expired. Sign in again.");
  const ok = u["two_factor_method"] === "totp" ? totpOk(decrypt(u["totp_secret_enc"]), code) : sameHash(u["code_hash"], keyed(`${challengeId}:${code}`));
  if (!ok) { await fail(u); throw new DomainError(422, "CODE_INVALID", "The code is not correct."); }
  const used = await execute(pool, "UPDATE email_otp_challenges SET used_at=UTC_TIMESTAMP(3) WHERE id=? AND used_at IS NULL", [challengeId]);
  if (!used.affectedRows) throw new DomainError(410, "CHALLENGE_EXPIRED", "This code has expired. Sign in again.");
  await startSession(c, u["id"], Boolean(u["remember"]));
  return { status: u["must_change_password"] ? "password_change_required" : "ok" };
}
export async function resend2fa(challengeId: string) {
  const u = await challenge(challengeId);
  if (!u) throw new DomainError(410, "CHALLENGE_EXPIRED", "This code has expired. Sign in again.");
  if (u["two_factor_method"] !== "totp") await sendCode(challengeId, u);
  return { ok: true };
}
export function checkPassword(password: string, path = "new"): void {
  if (password.length < 10) invalid(path, "Use at least 10 characters.");
  if (password.length > 72) invalid(path, "Use at most 72 characters.");
  if (!/[a-z]/i.test(password) || !/\d/.test(password)) invalid(path, "Use letters and at least one number.");
}
async function setPassword(db: Db, userId: string, password: string, keepSession?: string): Promise<void> {
  await execute(db, "UPDATE users SET password_hash=?, must_change_password=0, password_changed_at=UTC_TIMESTAMP(3), failed_login_count=0, locked_until=NULL WHERE id=?", [await bcrypt.hash(password, 12), userId]);
  await execute(db, "UPDATE user_sessions SET revoked_at=UTC_TIMESTAMP(3) WHERE user_id=? AND revoked_at IS NULL AND id<>?", [userId, keepSession ?? "0"]);
}
export async function changePassword(c: Ctx, current: string, next: string) {
  checkPassword(next);
  const u = (await one(pool, "SELECT password_hash FROM users WHERE id=?", [c.user.id]))!;
  if (!(await bcrypt.compare(current, u["password_hash"]))) invalid("current", "Current password is not correct.");
  if (await bcrypt.compare(next, u["password_hash"])) invalid("new", "Choose a password you are not using now.");
  await transaction(async (tx) => { await setPassword(tx, c.user.id, next, c.user.sessionId); await audit(tx, c, { module: "identity", action: "password_changed", entityType: "user", entityId: c.user.id, summary: "Changed own password" }); });
  return { ok: true };
}
/** Creates a one-time link. Only its hash is stored. */
export async function issueLink(db: Db, userId: string, purpose: "invite" | "password_reset", hours: number): Promise<string> {
  await execute(db, "UPDATE user_tokens SET used_at=UTC_TIMESTAMP(3) WHERE user_id=? AND purpose=? AND used_at IS NULL", [userId, purpose]);
  const token = randomToken();
  await execute(db, "INSERT INTO user_tokens (user_id, purpose, token_hash, expires_at) VALUES (?,?,?,UTC_TIMESTAMP(3)+INTERVAL ? HOUR)", [userId, purpose, sha256(token), hours]);
  return `${env.APP_URL}/${purpose === "invite" ? "invite" : "reset-password"}?token=${token}`;
}
export async function inviteMail(db: Db, userId: string, name: string, email: string, projectId?: string): Promise<void> {
  const link = await issueLink(db, userId, "invite", 72);
  await queueMail(db, { to: email, subject: "You are invited to PBPS MIS", text: `Hello ${name},\nOpen this link to choose your password. It works for 3 days.\n${link}`, template: "auth.invite", ...(projectId ? { projectId } : {}) });
}
/** An administrator sets the password (V1 "set password"). Every session ends; the person must choose their own at next sign-in. */
export async function adminSetPassword(db: Db, userId: string, password: string): Promise<void> {
  checkPassword(password, "password");
  await execute(db, "UPDATE users SET password_hash=?, must_change_password=1, password_changed_at=UTC_TIMESTAMP(3), failed_login_count=0, locked_until=NULL WHERE id=?", [await bcrypt.hash(password, 12), userId]);
  await execute(db, "UPDATE user_sessions SET revoked_at=UTC_TIMESTAMP(3) WHERE user_id=? AND revoked_at IS NULL", [userId]);
}
/** Letters and digits only, so it can be read out on the phone. */
export const generatePassword = (): string => { const a = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", d = "23456789", all = a + d; return a[randomInt(a.length)]! + Array.from({ length: 10 }, () => all[randomInt(all.length)]).join("") + d[randomInt(d.length)]!; };
/** A reset link sent by an administrator works for one day. The link is returned too, for when email is switched off. */
export async function resetLinkMail(db: Db, userId: string, name: string, email: string, projectId?: string): Promise<string> {
  const link = await issueLink(db, userId, "password_reset", 24);
  await queueMail(db, { to: email, subject: "Reset your PBPS MIS password", text: `Hello ${name},
Open this link to choose a new password. It works for 24 hours.
${link}`, template: "auth.reset", ...(projectId ? { projectId } : {}) });
  return link;
}
export async function forgotPassword(email: string) {
  const u = await one(pool, "SELECT id, name, email FROM users WHERE email=? AND status='active'", [email.trim().toLowerCase()]);
  if (u) await queueMail(pool, { to: u["email"], subject: "Reset your PBPS MIS password", text: `Hello ${u["name"]},\nOpen this link to choose a new password. It works for 1 hour.\n${await issueLink(pool, u["id"], "password_reset", 1)}`, template: "auth.reset" });
  return { ok: true };
}
const token = (purpose: string, raw: string) => one(pool, "SELECT t.id AS tid, u.* FROM user_tokens t JOIN users u ON u.id=t.user_id WHERE t.token_hash=? AND t.purpose=? AND t.used_at IS NULL AND t.expires_at>UTC_TIMESTAMP(3) AND u.status<>'disabled'", [sha256(raw), purpose]);
const expired = () => new DomainError(410, "TOKEN_EXPIRED", "This link has expired. Ask for a new one.");
async function consume(purpose: string, raw: string, password: string, path: string, after?: (tx: Db, u: Row) => Promise<void>): Promise<Row> {
  checkPassword(password, path);
  const u = await token(purpose, raw);
  if (!u) throw expired();
  await transaction(async (tx) => {
    if (!(await execute(tx, "UPDATE user_tokens SET used_at=UTC_TIMESTAMP(3) WHERE id=? AND used_at IS NULL", [u["tid"]])).affectedRows) throw expired();
    await setPassword(tx, u["id"], password);
    await after?.(tx, u);
  });
  return u;
}
export const resetPassword = async (raw: string, password: string) => { await consume("password_reset", raw, password, "new"); return { ok: true }; };
export async function getInvite(raw: string) {
  const u = await token("invite", raw);
  if (!u) throw expired();
  const m = await one(pool, "SELECT r.label, p.name AS provider FROM memberships m JOIN roles r ON r.id=m.role_id LEFT JOIN providers p ON p.id=m.provider_id WHERE m.user_id=? ORDER BY m.id LIMIT 1", [u["id"]]);
  return { name: u["name"], email: u["email"], roleLabel: m?.["label"] ?? "", ...(m?.["provider"] ? { providerName: m["provider"] } : {}), requires2fa: (await needs2fa(u)) !== "none" };
}
export async function acceptInvite(c: Ctx, raw: string, name: string, password: string) {
  const u = await consume("invite", raw, password, "password", async (tx, x) => { await execute(tx, "UPDATE users SET status='active', name=?, email_verified_at=UTC_TIMESTAMP(3) WHERE id=?", [name, x["id"]]); });
  await startSession(c, u["id"], false);
  return { ok: true };
}
export const listSessions = async (c: Ctx) => (await query(pool, "SELECT id, ip, user_agent, last_used_at FROM user_sessions WHERE user_id=? AND revoked_at IS NULL AND expires_at>UTC_TIMESTAMP(3) ORDER BY last_used_at DESC", [c.user.id]))
  .map((s) => ({ id: String(s["id"]), device: s["user_agent"] || "Unknown device", ip: s["ip"] ?? "", lastUsed: s["last_used_at"], current: String(s["id"]) === c.user.sessionId }));
export const revokeSession = async (c: Ctx, sessionId: string) => { await execute(pool, "UPDATE user_sessions SET revoked_at=UTC_TIMESTAMP(3) WHERE id=? AND user_id=?", [sessionId, c.user.id]); };
export async function logout(c: Ctx) { if (c.user) await revokeSession(c, c.user.sessionId); clearCookies(c.reply); }
export async function setupTotp(c: Ctx) {
  const secret = newTotpSecret();
  await execute(pool, "UPDATE users SET totp_secret_enc=IF(two_factor_method='totp', totp_secret_enc, ?) WHERE id=?", [encrypt(secret), c.user.id]);
  if (c.user.twoFactorMethod === "totp") throw new DomainError(409, "TOTP_ACTIVE", "An authenticator app is already set up.");
  return { secret, otpauthUrl: `otpauth://totp/PBPS%20MIS:${encodeURIComponent(c.user.email)}?secret=${secret}&issuer=PBPS%20MIS` };
}
export async function confirmTotp(c: Ctx, code: string) {
  const u = (await one(pool, "SELECT totp_secret_enc AS s FROM users WHERE id=?", [c.user.id]))!;
  if (!u["s"] || !totpOk(decrypt(u["s"]), code)) throw new DomainError(422, "CODE_INVALID", "Enter the 6-digit code from your app.");
  await execute(pool, "UPDATE users SET two_factor_method='totp' WHERE id=?", [c.user.id]);
  return { ok: true };
}
export async function me(c: Ctx) {
  const rows = await query(pool, "SELECT m.project_id AS projectId, p.code AS projectCode, p.title AS projectTitle, r.code AS roleCode, r.label AS roleLabel, m.provider_id AS providerId, t.name AS providerName FROM memberships m JOIN projects p ON p.id=m.project_id JOIN roles r ON r.id=m.role_id LEFT JOIN providers t ON t.id=m.provider_id WHERE m.user_id=? AND m.status='active' ORDER BY m.id", [c.user.id]);
  return { user: { id: c.user.id, name: c.user.name, email: c.user.email, mustChangePassword: c.user.mustChangePassword, twoFactorMethod: c.user.twoFactorMethod }, memberships: rows.map((r) => Object.fromEntries(Object.entries(r).filter(([, v]) => v !== null))) };
}
export async function createUser(db: Db, name: string, email: string): Promise<{ id: string; isNew: boolean }> {
  const e = email.trim().toLowerCase();
  const old = await one(db, "SELECT id FROM users WHERE email=?", [e]);
  if (old) return { id: String(old["id"]), isNew: false };
  return { id: await insert(db, "users", { name, email: e, password_hash: await bcrypt.hash(randomToken().slice(0, 60), 12), status: "invited", two_factor_method: "none" }), isNew: true };
}
