import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { IsDateString, IsIn, IsNumber, IsOptional, IsString, IsUUID, MaxLength, Min } from 'class-validator';
import {
  RATE_APPLIES_TO,
  RATE_TRIGGERS,
  RATE_UNITS,
} from '../entities/rate.entity';

const TRADE_DIRECTIONS = ['IMPORT', 'EXPORT', 'BOTH'] as const;
const CURRENCIES = ['USD'] as const;

export class CreateRateDto {
  @ApiProperty({ enum: RATE_APPLIES_TO, description: 'Friendly category the rate applies to' })
  @IsIn([...RATE_APPLIES_TO])
  appliesTo!: string;

  @ApiProperty({
    enum: RATE_TRIGGERS,
    description: 'What makes this rate apply. ALWAYS = base freight; anything else is a surcharge.',
  })
  @IsIn([...RATE_TRIGGERS])
  trigger!: string;

  @ApiPropertyOptional({ description: 'FK to container_types.id — set for container/intercity-container rates' })
  @IsOptional()
  @IsUUID()
  containerTypeId?: string;

  @ApiPropertyOptional({ description: 'FK to cargo_types.id (bulk leaf commodity) — set for bulk/intercity-bulk rates' })
  @IsOptional()
  @IsUUID()
  cargoTypeId?: string;

  @ApiPropertyOptional({ enum: TRADE_DIRECTIONS, description: 'Trade direction. Null = direction-agnostic' })
  @IsOptional()
  @IsIn([...TRADE_DIRECTIONS])
  tradeDirection?: string;

  @ApiPropertyOptional({ enum: CURRENCIES })
  @IsOptional()
  @IsIn([...CURRENCIES])
  currency?: string;

  @ApiProperty({ description: 'Numeric rate value', minimum: 0 })
  @IsNumber()
  @Min(0)
  @Transform(({ value }) => Number(value))
  rateValue!: number;

  @ApiProperty({ enum: RATE_UNITS, description: 'Unit basis for the rate' })
  @IsIn([...RATE_UNITS])
  rateUnit!: string;

  @ApiProperty({ description: 'Date from which this rate is effective (ISO date)', example: '2025-01-01' })
  @IsDateString()
  effectiveFrom!: string;

  @ApiPropertyOptional({ description: 'Date when this rate expires. Null = currently active', example: '2025-12-31' })
  @IsOptional()
  @IsDateString()
  effectiveTo?: string;
}

export class SubmitRateForApprovalDto {
  @ApiPropertyOptional({ description: 'Optional note for the approval request', maxLength: 500 })
  @IsOptional()
  @IsString()
  @MaxLength(500)
  note?: string;
}
