import { type Application, type Request, type Response, type RequestHandler } from 'express';
import type { Repository } from '../db/repository.js';
import { requireAdmin } from './auth.js';

const passthrough: RequestHandler = (_req, _res, next) => next();

export function mountAdminApi(app: Application, repo: Repository, authActive = true): void {
  const guard = authActive ? requireAdmin : passthrough;

  app.get('/api/admin/users', guard, (_req: Request, res: Response) => {
    const users = authActive ? repo.listUsers() : [];
    const enriched = users.map(u => ({
      ...u,
      orgs: repo.listUserGiteaOrgs(u.id),
    }));
    res.json(enriched);
  });

  app.patch('/api/admin/users/:id', guard, (req: Request, res: Response) => {
    if (!authActive) { res.status(403).json({ error: 'Auth is not configured' }); return; }
    const { id } = req.params;
    const { status, role } = req.body;
    const user = repo.getUserById(id);
    if (!user) {
      res.status(404).json({ error: 'User not found' });
      return;
    }
    repo.updateUser(id, { status, role });

    // Invalidate sessions on status/role change
    if (status === 'disabled' || status === 'pending' || role) {
      repo.deleteSessionsByUserId(id);
    }

    const updated = repo.getUserById(id);
    res.json(updated);
  });

  app.delete('/api/admin/users/:id', guard, (req: Request, res: Response) => {
    if (!authActive) { res.status(403).json({ error: 'Auth is not configured' }); return; }
    const { id } = req.params;
    const user = repo.getUserById(id);
    if (!user) {
      res.status(404).json({ error: 'User not found' });
      return;
    }
    repo.deleteSessionsByUserId(id);
    repo.deleteUser(id);
    res.status(204).end();
  });
}
