import { createHash, randomBytes, randomUUID } from "node:crypto";
import { hash, verify } from "@node-rs/argon2";
import type { FastifyReply } from "fastify";

export const INVITATION_TTL_MS = 7 * 24 * 60 * 60 * 1000;
export const SESSION_TTL_MS = 400 * 24 * 60 * 60 * 1000;

export const sessionCookieName = process.env.COOKIE_SECURE === "true"
  ? "__Host-cents_session"
  : "cents_session";

export function createSecret() {
  return randomBytes(32).toString("base64url");
}

export function hashSecret(secret: string) {
  return createHash("sha256").update(secret).digest("hex");
}

export function createId() {
  return randomUUID();
}

export function normalizeName(name: string) {
  return name.trim().toLocaleLowerCase("zh-CN");
}

export function validPassword(password: string) {
  return password.length >= 8 && password.length <= 128;
}

export function hashPassword(password: string) {
  return hash(password, {
    memoryCost: 19_456,
    timeCost: 2,
    parallelism: 1,
    outputLen: 32,
  });
}

export function verifyPassword(passwordHash: string, password: string) {
  return verify(passwordHash, password);
}

export function setSessionCookie(reply: FastifyReply, token: string) {
  reply.setCookie(sessionCookieName, token, {
    path: "/",
    httpOnly: true,
    secure: process.env.COOKIE_SECURE === "true",
    sameSite: "lax",
    maxAge: SESSION_TTL_MS / 1000,
  });
}

export function clearSessionCookie(reply: FastifyReply) {
  reply.clearCookie(sessionCookieName, {
    path: "/",
    secure: process.env.COOKIE_SECURE === "true",
    sameSite: "lax",
  });
}
