import { Router } from 'express';
import { clearSessionCookie, currentSession, login, logout, setSessionCookie } from '../auth.js';
import { createAuditEvent } from '../store.js';

export const authRouter = Router();

authRouter.get('/session', (req, res) => {
  const session = currentSession(req);
  res.json({ authenticated: Boolean(session), user: session?.user || null });
});

authRouter.post('/login', (req, res) => {
  const result = login(req.body?.username, req.body?.password);
  if (!result) {
    res.status(401).json({ error: 'Invalid username or password.' });
    return;
  }
  setSessionCookie(res, result.session);
  createAuditEvent({
    user: result.user,
    action: 'login',
    targetType: 'session',
    targetId: result.session.id,
  });
  res.json({ user: result.user });
});

authRouter.post('/logout', (req, res) => {
  const session = currentSession(req);
  if (session) {
    createAuditEvent({
      user: session.user,
      action: 'logout',
      targetType: 'session',
      targetId: session.sessionId,
    });
  }
  logout(session?.sessionId);
  clearSessionCookie(res);
  res.json({ ok: true });
});
