import {
  Controller,
  Get,
  Post,
  Delete,
  Body,
  Param,
} from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { ApiKeysService } from './api-keys.service';
import { CreateApiKeyDto } from './dto/create-api-key.dto';
import { CurrentTenant } from '../../common/decorators/current-tenant.decorator';
import { RequirePermission } from '../../common/decorators/require-permission.decorator';

@ApiTags('api-keys')
@ApiBearerAuth()
@Controller('api-keys')
export class ApiKeysController {
  constructor(private readonly apiKeysService: ApiKeysService) {}

  @Post()
  @RequirePermission('apikeys.manage')
  @ApiOperation({
    summary: 'Create an API key',
    description:
      'Issues a new API key for this license. The full plaintext key is returned ONCE — store it securely; it cannot be retrieved again.',
  })
  @ApiResponse({ status: 201, description: 'Key created — plaintext key returned once.' })
  async create(
    @CurrentTenant() licenseId: string,
    @Body() dto: CreateApiKeyDto,
  ) {
    return this.apiKeysService.create(licenseId, dto.name);
  }

  @Get()
  @RequirePermission('apikeys.view')
  @ApiOperation({ summary: 'List API keys', description: 'Returns all keys (active and revoked) for this license. Key hashes are never returned.' })
  @ApiResponse({ status: 200, description: 'Key list.' })
  async list(@CurrentTenant() licenseId: string) {
    return this.apiKeysService.list(licenseId);
  }

  @Delete(':id')
  @RequirePermission('apikeys.manage')
  @ApiOperation({ summary: 'Revoke an API key', description: 'Soft-deletes the key (is_active = false). The row is retained for audit purposes.' })
  @ApiResponse({ status: 200, description: 'Key revoked.' })
  @ApiResponse({ status: 404, description: 'Key not found in this license.' })
  async revoke(
    @CurrentTenant() licenseId: string,
    @Param('id') id: string,
  ) {
    return this.apiKeysService.revoke(licenseId, id);
  }
}
