import { Controller, Get, Post, Patch, Delete, Param, Body, SetMetadata } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { IsEnum, IsNumber, IsOptional, IsString, Min } from 'class-validator';
import { Currency } from '@prisma/client';
import { CurrencyService } from './currency.service';
import { PassengerAdmin } from '../../common/passenger-guards';

class CreateRateDto {
  @IsEnum(Currency) fromCurrency: Currency;
  @IsEnum(Currency) toCurrency: Currency;
  @IsNumber() @Min(0.000001) rate: number;
  @IsOptional() @IsString() source?: string;
}

class UpdateRateDto {
  @IsNumber() @Min(0.000001) rate: number;
  @IsOptional() @IsString() source?: string;
}

@ApiTags('Currency')
@Controller('currencies')
export class CurrencyController {
  constructor(private readonly currencyService: CurrencyService) {}

  @Get()
  @SetMetadata('isPublic', true)
  @ApiOperation({ summary: 'List all exchange rates' })
  listRates() {
    return this.currencyService.listRates();
  }

  @Post()
  @PassengerAdmin()
  @ApiBearerAuth('IAM-auth')
  @ApiOperation({ summary: 'Create exchange rate' })
  create(@Body() dto: CreateRateDto) {
    return this.currencyService.upsertRate(dto.fromCurrency, dto.toCurrency, dto.rate, undefined, dto.source ?? 'MANUAL');
  }

  @Patch(':id')
  @PassengerAdmin()
  @ApiBearerAuth('IAM-auth')
  @ApiOperation({ summary: 'Update exchange rate by ID' })
  update(@Param('id') id: string, @Body() dto: UpdateRateDto) {
    return this.currencyService.updateRateById(id, dto.rate, dto.source ?? 'MANUAL');
  }

  @Delete(':id')
  @PassengerAdmin()
  @ApiBearerAuth('IAM-auth')
  @ApiOperation({ summary: 'Delete exchange rate by ID' })
  delete(@Param('id') id: string) {
    return this.currencyService.deleteRate(id);
  }
}
