import { ApiPropertyOptional } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { IsDateString, IsIn, IsOptional, IsUUID } from 'class-validator';

import { CONTRACT_STATUSES, CONTRACT_KINDS } from '../entities/contract.entity';

const TRADE_DIRECTIONS = ['IMPORT', 'EXPORT', 'DOMESTIC'] as const;
const FREIGHT_TYPES = ['CONTAINER', 'BULK'] as const;
const PAYMENT_CURRENCIES = ['ETB', 'USD'] as const;

export class FilterContractDto {
  @ApiPropertyOptional({ enum: CONTRACT_STATUSES })
  @IsOptional()
  @IsIn([...CONTRACT_STATUSES])
  status?: string;

  @ApiPropertyOptional({
    description:
      'Filter by statuses: comma-separated or repeated query params. Overrides status when set.',
  })
  @IsOptional()
  @Transform(({ value }) => {
    if (value === undefined || value === null || value === '') return undefined;
    if (Array.isArray(value)) return value.map(String).join(',');
    return String(value);
  })
  statuses?: string;

  @ApiPropertyOptional({ format: 'uuid' })
  @IsOptional()
  @IsUUID()
  companyId?: string;

  @ApiPropertyOptional({ format: 'uuid' })
  @IsOptional()
  @IsUUID()
  companyProfileId?: string;

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

  @ApiPropertyOptional({ format: 'uuid' })
  @IsOptional()
  @IsUUID()
  serviceTypeId?: string;

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

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

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

  @ApiPropertyOptional({ description: 'Filter contracts created on/after this date (ISO)' })
  @IsOptional()
  @IsDateString()
  createdFrom?: string;

  @ApiPropertyOptional({ description: 'Filter contracts created on/before this date (ISO)' })
  @IsOptional()
  @IsDateString()
  createdTo?: string;

  @ApiPropertyOptional({
    description: 'Free-text search across contract reference and company name.',
  })
  @IsOptional()
  @Transform(({ value }) =>
    typeof value === 'string' && value.trim() ? value.trim() : undefined,
  )
  search?: string;

  @ApiPropertyOptional({ default: 1 })
  @IsOptional()
  @Transform(({ value }) => (value ? parseInt(value, 10) : 1))
  page?: number;

  @ApiPropertyOptional({ default: 20 })
  @IsOptional()
  @Transform(({ value }) => (value ? parseInt(value, 10) : 20))
  pageSize?: number;

  @ApiPropertyOptional({ default: 'createdAt' })
  @IsOptional()
  @IsIn(['createdAt', 'contractValidUntil'])
  sortBy?: string;

  @ApiPropertyOptional({ enum: ['ASC', 'DESC'], default: 'DESC' })
  @IsOptional()
  @IsIn(['ASC', 'DESC'])
  sortOrder?: 'ASC' | 'DESC';
}
