import { Body, Controller, Delete, Get, Param, Patch, Put, Post } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiParam, ApiProperty, ApiResponse } from '@nestjs/swagger';
import { CurrencyService } from '../currency/currency.service';
import { UpsertExchangeRateDto } from './currency.dto';
import { IsNumber, IsPositive, IsOptional, IsString } from 'class-validator';
import { Type } from 'class-transformer';

class UpdateExchangeRateDto {
  @ApiProperty({ example: 3.5 }) @Type(() => Number) @IsNumber() @IsPositive() rate: number;
  @ApiProperty({ example: 'MANUAL', required: false }) @IsOptional() @IsString() source?: string;
}

@ApiTags('Fare Engine')
@Controller('fare-engine/exchange-rates')
export class CurrencyController {
  constructor(private currency: CurrencyService) {}

  @Get()
  @ApiOperation({ summary: 'List all exchange rates (latest per pair first)' })
  list() {
    return this.currency.listRates();
  }

  @Put()
  @ApiOperation({ summary: 'Upsert an exchange rate for today' })
  @ApiResponse({ status: 200, description: 'Rate created or updated for today\'s effective date' })
  upsert(@Body() dto: UpsertExchangeRateDto) {
    return this.currency.upsertRate(dto.fromCurrency, dto.toCurrency, dto.rate, undefined, dto.source);
  }

  @Patch(':id')
  @ApiOperation({ summary: 'Update an exchange rate by ID' })
  @ApiParam({ name: 'id', description: 'CurrencyExchangeRate UUID' })
  @ApiResponse({ status: 200, description: 'Rate updated' })
  @ApiResponse({ status: 404, description: 'Rate not found' })
  update(@Param('id') id: string, @Body() dto: UpdateExchangeRateDto) {
    return this.currency.updateRateById(id, dto.rate, dto.source);
  }

  @Delete(':id')
  @ApiOperation({ summary: 'Delete an exchange rate record by ID' })
  @ApiParam({ name: 'id', description: 'CurrencyExchangeRate UUID' })
  @ApiResponse({ status: 200, description: 'Rate deleted' })
  @ApiResponse({ status: 404, description: 'Rate not found' })
  remove(@Param('id') id: string) {
    return this.currency.deleteRate(id);
  }

  @Post('sync')
  @ApiOperation({ summary: 'Trigger exchange rate sync from external provider' })
  sync() {
    return this.currency.syncExchangeRates();
  }
}
