import type { Response } from "express";
import type { RequestWithCookies } from "@bff/modules/auth/auth.types.js";
import { getSecureCookie } from "./secure-cookie.util.js";

/**
 * Cookie name for trusted device token
 */
export const TRUSTED_DEVICE_COOKIE_NAME = "trusted_device";

/**
 * Cookie path - applies to all auth endpoints
 */
export const TRUSTED_DEVICE_COOKIE_PATH = "/api/auth";

/**
 * Set the trusted device cookie on the response
 *
 * @param res - Express response object
 * @param token - The signed JWT token
 * @param ttlMs - Time to live in milliseconds
 */
export function setTrustedDeviceCookie(res: Response, token: string, ttlMs: number): void {
  const setSecureCookie = getSecureCookie(res);

  if (setSecureCookie) {
    // Use the custom setSecureCookie helper if available
    setSecureCookie(TRUSTED_DEVICE_COOKIE_NAME, token, {
      maxAge: ttlMs,
      path: TRUSTED_DEVICE_COOKIE_PATH,
    });
  } else {
    // Fallback to standard cookie with secure options
    const isProduction = process.env["NODE_ENV"] === "production";

    res.cookie(TRUSTED_DEVICE_COOKIE_NAME, token, {
      httpOnly: true,
      secure: isProduction,
      sameSite: "lax",
      path: TRUSTED_DEVICE_COOKIE_PATH,
      maxAge: ttlMs,
    });
  }
}

/**
 * Clear the trusted device cookie
 *
 * @param res - Express response object
 */
export function clearTrustedDeviceCookie(res: Response): void {
  const setSecureCookie = getSecureCookie(res);

  if (setSecureCookie) {
    setSecureCookie(TRUSTED_DEVICE_COOKIE_NAME, "", {
      maxAge: 0,
      path: TRUSTED_DEVICE_COOKIE_PATH,
    });
  } else {
    const isProduction = process.env["NODE_ENV"] === "production";

    res.cookie(TRUSTED_DEVICE_COOKIE_NAME, "", {
      httpOnly: true,
      secure: isProduction,
      sameSite: "lax",
      path: TRUSTED_DEVICE_COOKIE_PATH,
      maxAge: 0,
    });
  }
}

/**
 * Get the trusted device token from the request cookies
 *
 * @param req - Express request object
 * @returns The token string or undefined if not present
 */
export function getTrustedDeviceToken(req: RequestWithCookies): string | undefined {
  return req.cookies?.[TRUSTED_DEVICE_COOKIE_NAME];
}
