import { Body, Controller, Get, Param, Patch, Req, UseGuards } from '@nestjs/common';
import { OperationLog } from '../audit/operation-log.decorator';
import { AuthGuard } from '../auth/auth.guard';
import type { AuthenticatedRequest } from '../auth/types/authenticated-request';
import { AdminPermissionsService } from './admin-permissions.service';

@UseGuards(AuthGuard)
@Controller('api/admin/permissions')
export class AdminPermissionsController {
  constructor(private readonly permissionsService: AdminPermissionsService) {}

  @Get()
  list(@Req() request: AuthenticatedRequest) {
    return this.permissionsService.listPermissions(request.user);
  }

  @Patch('roles/:code')
  @OperationLog({
    action: 'admin.permissions.update_role',
    resourceType: 'role',
    resourceIdParam: 'code',
    metadataFromBody: ['permissions'],
    description: '更新角色权限',
  })
  updateRole(
    @Req() request: AuthenticatedRequest,
    @Param('code') code: string,
    @Body() body: { permissions?: Record<string, string[]> },
  ) {
    return this.permissionsService.updateRolePermissions(
      request.user,
      code,
      body.permissions || {},
    );
  }
}
