import type { RequestHandler } from 'express';
import { env } from '../config/env';
import { db } from '../db/knex';
import { COOKIE_NAME, REFRESH_AFTER_MIN, setAuthCookie, verifyToken, type Role } from '../lib/auth';
import { forbidden, unauthorized } from '../lib/http-errors';

export type AuthAdmin = {
  id: string;
  name: string;
  email: string;
  role: Role;
  status: 'active' | 'invited' | 'disabled';
  last_login_at: string | null;
};

declare module 'express-serve-static-core' {
  interface Locals {
    admin?: AuthAdmin;
  }
}

/** Requires a valid admin cookie and an active account; refreshes the cookie on activity. */
export const requireAdmin: RequestHandler = async (req, res, next) => {
  const token = req.cookies?.[COOKIE_NAME];
  const payload = token ? verifyToken(token) : null;
  if (!payload) return next(unauthorized());
  const admin = (await db('admins')
    .select('id', 'name', 'email', 'role', 'status', 'last_login_at')
    .where({ id: payload.sub })
    .first()) as AuthAdmin | undefined;
  if (!admin || admin.status !== 'active')
    return next(unauthorized('Your session has ended. Please sign in again.'));
  res.locals.admin = { ...admin, id: String(admin.id) };
  // sliding session: re-issue when older than REFRESH_AFTER_MIN (role changes take effect too)
  if (payload.iat && Date.now() / 1000 - payload.iat > REFRESH_AFTER_MIN * 60)
    setAuthCookie(res, String(admin.id), admin.role);
  next();
};

export const requireRole =
  (...roles: Role[]): RequestHandler =>
  (_req, res, next) => {
    const role = res.locals.admin?.role;
    if (!role || !roles.includes(role)) return next(forbidden('Your role does not allow this.'));
    next();
  };

/**
 * CSRF defence for cookie auth: state-changing admin requests must come from an allowed origin.
 * (SameSite=Lax already blocks most cross-site POSTs; this closes the rest.)
 */
export const originCheck: RequestHandler = (req, _res, next) => {
  if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next();
  const origin = req.get('origin') ?? (req.get('referer') ? new URL(req.get('referer')!).origin : undefined);
  const allowed = [...env.CORS_ORIGINS, env.ADMIN_URL];
  if (!origin) return env.NODE_ENV === 'production' ? next(forbidden('Missing Origin header.')) : next();
  if (!allowed.includes(origin)) return next(forbidden('Request origin is not allowed.'));
  next();
};
