import { Body, Controller, Delete, Get, Param, Post, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { CurrentPrincipal } from '../auth/decorators/current-user.decorator';
import { Roles } from '../auth/decorators/roles.decorator';
import { JwtAuthGuard } from '../auth/guards/auth.guard';
import { OrgRolesGuard } from '../auth/guards/org-roles.guard';
import { UserPrincipal } from '../auth/principal';
import { ApiKeysService } from './api-keys.service';
import { CreateApiKeyDto } from './dto/api-keys.dto';

// JWT-only by design: an API key must not be able to mint or revoke API keys
@ApiTags('api-keys')
@ApiBearerAuth('jwt')
@Controller('orgs/:orgId/api-keys')
@UseGuards(JwtAuthGuard, OrgRolesGuard)
@Roles('ORG_ADMIN')
export class ApiKeysController {
  constructor(private readonly apiKeysService: ApiKeysService) {}

  @Get()
  list(@Param('orgId') orgId: string) {
    return this.apiKeysService.list(orgId);
  }

  @Post()
  create(
    @Param('orgId') orgId: string,
    @Body() dto: CreateApiKeyDto,
    @CurrentPrincipal() principal: UserPrincipal,
  ) {
    return this.apiKeysService.create(orgId, dto, principal.userId);
  }

  @Delete(':keyId')
  revoke(@Param('orgId') orgId: string, @Param('keyId') keyId: string) {
    return this.apiKeysService.revoke(orgId, keyId);
  }
}
