import { Controller, Get, Query, Req } from "@nestjs/common";
import { IamRepository } from "./iam.repository.js";
import {
  Permissions,
  RequirePermission,
} from "../middleware/permission.guard.js";
import type { AuthenticatedRequest } from "../middleware/auth.middleware.js";

/**
 * 审计日志查询端点（president §5.5：审计日志归 iam）。
 *
 * 路径前缀：/v1/iam
 * 端点：GET /v1/iam/audit
 */
@Controller("v1/iam")
export class AuditController {
  constructor(private readonly repository: IamRepository) {}

  @Get("audit")
  @RequirePermission(Permissions.IAM_AUDIT_READ)
  async queryAudit(
    @Query("actorUserId") actorUserId: string | undefined,
    @Query("resourceType") resourceType: string | undefined,
    @Query("resourceId") resourceId: string | undefined,
    @Query("limit") limitStr: string | undefined,
    @Query("offset") offsetStr: string | undefined,
    @Req() _req: AuthenticatedRequest,
  ): Promise<{ success: true; data: unknown[] }> {
    const limit = limitStr ? Number.parseInt(limitStr, 10) : 50;
    const offset = offsetStr ? Number.parseInt(offsetStr, 10) : 0;
    const data = await this.repository.queryAuditLog({
      actorUserId,
      resourceType,
      resourceId,
      limit: Number.isNaN(limit) ? 50 : limit,
      offset: Number.isNaN(offset) ? 0 : offset,
    });
    return { success: true as const, data };
  }
}
