import {
  Controller,
  Post,
  Get,
  Delete,
  Patch,
  Param,
  Body,
  UseGuards,
  NotFoundException,
} from '@nestjs/common';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { CurrentUser } from '../auth/decorators/current-user.decorator';
import { User } from '../../entities/user.entity';
import { ApiKeysService } from './api-keys.service';

@Controller('api/api-keys')
@UseGuards(JwtAuthGuard)
export class ApiKeysController {
  constructor(private readonly apiKeysService: ApiKeysService) {}

  @Post()
  async create(
    @CurrentUser() user: User,
    @Body('name') name: string,
  ) {
    const { apiKey, rawKey } = await this.apiKeysService.create(user.id, name);
    return {
      id: apiKey.id,
      name: apiKey.name,
      key: rawKey,
      keyPrefix: apiKey.keyPrefix,
      createdAt: apiKey.createdAt,
      message: 'Store this key securely — it will not be shown again.',
    };
  }

  @Get()
  async list(@CurrentUser() user: User) {
    const keys = await this.apiKeysService.listByUser(user.id);
    return keys.map((k) => ({
      id: k.id,
      name: k.name,
      keyPrefix: k.keyPrefix,
      isActive: k.isActive,
      lastUsedAt: k.lastUsedAt,
      createdAt: k.createdAt,
    }));
  }

  @Patch(':id/revoke')
  async revoke(@CurrentUser() user: User, @Param('id') id: string) {
    const ok = await this.apiKeysService.revoke(id, user.id);
    if (!ok) throw new NotFoundException('API key not found');
    return { success: true };
  }

  @Delete(':id')
  async remove(@CurrentUser() user: User, @Param('id') id: string) {
    const ok = await this.apiKeysService.delete(id, user.id);
    if (!ok) throw new NotFoundException('API key not found');
    return { success: true };
  }
}
