import { Router } from 'express';
import bcrypt from 'bcryptjs';
import { z } from 'zod';
import { db } from '../../db/knex';
import { loginSchema } from '../../shared/schemas';
import { clearAuthCookie, setAuthCookie } from '../../lib/auth';
import { HttpError } from '../../lib/http-errors';
import { requireAdmin } from '../../middleware/auth';
import { loginLimiter } from '../../middleware/rateLimits';
import { validate } from '../../middleware/validate';
import { audit } from './audit';
import { toAdminUser } from './mappers';

// Compared against when the email doesn't exist, so response time doesn't reveal which emails are registered.
const DUMMY_HASH = bcrypt.hashSync('dummy-password-for-timing', 12);

export function authRouter() {
  const r = Router();

  r.post('/auth/login', loginLimiter, validate({ body: loginSchema }), async (_req, res) => {
    const { email, password, remember } = res.locals.valid!.body as z.infer<typeof loginSchema>;
    const admin = await db('admins').where({ email: email.toLowerCase() }).first();
    const ok = await bcrypt.compare(password, admin?.password_hash ?? DUMMY_HASH);
    if (!admin || !ok) throw new HttpError(401, 'invalid_credentials', 'Email or password is not correct.');
    if (admin.status !== 'active')
      throw new HttpError(403, 'inactive', 'This account is not active. Ask an admin to enable it.');
    await db('admins').where({ id: admin.id }).update({ last_login_at: db.fn.now() });
    await audit({
      adminId: String(admin.id),
      action: 'login',
      entity: 'admin',
      entityId: admin.id,
      label: admin.email,
    });
    setAuthCookie(res, String(admin.id), admin.role, remember);
    res.json({ user: toAdminUser({ ...admin, last_login_at: new Date().toISOString() }) });
  });

  r.post('/auth/logout', (_req, res) => {
    clearAuthCookie(res);
    res.status(204).end();
  });

  r.get('/auth/me', requireAdmin, (_req, res) => res.json({ user: toAdminUser(res.locals.admin!) }));

  // Always 202 so the response never reveals whether an account exists. Email sending arrives with SMTP config.
  r.post(
    '/auth/forgot',
    loginLimiter,
    validate({ body: z.object({ email: z.string().email() }) }),
    (_req, res) => res.status(202).json({ ok: true }),
  );

  return r;
}
