import { Controller, Get, Req } from '@nestjs/common';
import { ApiCookieAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import type { Request } from 'express';
import { RequireAdmin } from './require-admin.decorator';

/**
 * `/api/admin/*` controllers per ADR-0020. The `@RequireAdmin()`
 * class-level decorator gates every route on the Entra `Portal.Admin`
 * role; downstream PRs will add per-method `@RequireMfa({ freshness: … })`
 * for the entry route.
 *
 * `GET /api/admin/me` is the self-test endpoint named in ADR-0020's
 * "Confirmation" §3 ("AdminModule with AdminRoleGuard + first
 * endpoint (`GET /api/admin/me` returning the session for
 * self-test)"). It lets ops verify the guard is wired correctly
 * (curl with no cookies → 401; curl with a non-admin session → 403
 * with an `admin.access_denied` audit row; curl with an admin
 * session → 200 + the public user payload) before any real admin
 * route ships.
 */
@ApiTags('admin (self-test)')
@ApiCookieAuth('portal_admin_session')
@Controller('admin')
@RequireAdmin()
export class AdminController {
  @ApiOperation({ summary: 'Self-test endpoint — current admin session payload + roles' })
  @Get('me')
  me(@Req() req: Request) {
    // `AdminRoleGuard` has already established that `req.session.user`
    // is present and has the `Portal.Admin` role — the handler can read the
    // field without re-checking. Using the non-null assertion keeps
    // the dead-branch noise out of the controller while leaving the
    // safety contract anchored in the guard's spec.
    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed by AdminRoleGuard
    const user = req.session.user!;
    return {
      oid: user.oid,
      tid: user.tid,
      username: user.username,
      displayName: user.displayName,
      roles: user.roles,
    };
  }
}
