import { BadRequestException, Body, Controller, Post, UseGuards } from '@nestjs/common';
import { ApiHeader, ApiTags } from '@nestjs/swagger';
import { InternalCryptoKeyGuard } from '../guards/internal-crypto-key.guard';
import { PublicApiCryptoService } from './public-api-crypto.service';

@ApiTags('Internal Crypto')
@ApiHeader({ name: 'x-api-key', required: true })
@UseGuards(InternalCryptoKeyGuard)
@Controller('internal/crypto')
export class CryptoToolsController {
  constructor(private readonly crypto: PublicApiCryptoService) {}

  @Post('encrypt')
  encrypt(@Body() body: unknown): string {
    return this.crypto.encrypt(body ?? null);
  }

  @Post('decrypt')
  decrypt(@Body() body: unknown): unknown {
    const value = this.crypto.tryDecrypt(this.getEncryptedBody(body));
    if (value === null) throw new BadRequestException('Invalid encrypted payload');
    return value;
  }

  private getEncryptedBody(body: unknown): unknown {
    if (typeof body === 'string') return body;
    if (body && typeof body === 'object') {
      return this.crypto.extractPayloadValue(body) ?? body;
    }
    return body;
  }
}
