/**
 * Login events REST endpoints for SmartAuth.
 *
 * GET /auth/login-events         — list login events for current user (Bearer)
 * GET /auth/login-events/admin   — list login events for any user (admin)
 */

import type { FastifyInstance } from 'fastify';
import { UnauthorizedError, ForbiddenError, BadRequestError } from '../../../lib/errors.js';
import * as loginEventRepo from './repository.js';

export async function loginEventRoutes(app: FastifyInstance) {
  // ── My Login Events ──────────────────────────────────────

  app.get('/auth/login-events', async req => {
    const payload = req.jwtPayload;
    if (!payload?.sub) throw new UnauthorizedError('Authentication required');

    const query = req.query as { limit?: string; result?: string; since?: string };
    const events = await loginEventRepo.listByUser(payload.sub, {
      limit: Number(query.limit) || 50,
      result: query.result,
      since: query.since,
    });

    return { events };
  });

  // ── Admin Login Events ────────────────────────────────────

  app.get('/auth/login-events/admin', async req => {
    const role = req.jwtPayload?.role;
    if (!role || !['super_admin', 'admin'].includes(role)) {
      throw new ForbiddenError('Admin access required');
    }

    const query = req.query as { userId?: string; limit?: string; result?: string; since?: string };
    if (!query.userId) {
      throw new BadRequestError('userId query parameter is required');
    }

    const events = await loginEventRepo.listByUser(query.userId, {
      limit: Number(query.limit) || 50,
      result: query.result,
      since: query.since,
    });

    return { events };
  });
}
