'use strict';

const express = require('express');
const rateLimit = require('express-rate-limit');
const { createToken, verifyToken, parseCookies, checkPassword } = require('../auth');

function buildAuthRoutes(opts) {
  const { SITE_PASSWORD, SESSION_SECRET, sessionHours, rateLimits } = opts;
  const router = express.Router();

  const loginLimiter = rateLimit({
    windowMs: 15 * 60 * 1000,
    max: rateLimits?.login_per_15min || 5,
    standardHeaders: true,
    legacyHeaders: false,
    handler: (req, res) => res.status(429).json({ error: 'Too many login attempts. Try again later.' }),
  });

  router.get('/check', (req, res) => {
    const cookies = parseCookies(req.headers.cookie);
    res.json({ authenticated: verifyToken(cookies.auth_token, SESSION_SECRET) });
  });

  router.post('/login', loginLimiter, (req, res) => {
    const submitted = req.body?.password;
    if (!checkPassword(String(submitted || ''), SITE_PASSWORD)) {
      return res.status(401).json({ error: 'Invalid password' });
    }
    const token = createToken(SESSION_SECRET, sessionHours);
    res.cookie('auth_token', token, {
      httpOnly: true,
      sameSite: 'strict',
      maxAge: sessionHours * 3600 * 1000,
    });
    res.json({ success: true });
  });

  router.post('/logout', (req, res) => {
    res.clearCookie('auth_token');
    res.json({ success: true });
  });

  return router;
}

module.exports = { buildAuthRoutes };
