import { ApiPropertyOptional, OmitType } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { IsDateString, IsIn, IsInt, IsOptional, IsString, IsUUID, Max, MaxLength, Min } from 'class-validator';

/** La pantalla vieja manda `cuentaId=&tipo=&…` con los filtros vacíos: vacío es «sin filtro» (F2). */
const vacioEsUndefined = ({ value }: { value: unknown }) => (value === '' ? undefined : value);
/** Igual que arriba, y los números llegan como texto del query string. NaN queda para que `IsInt` lo rechace. */
const numeroOUndefined = ({ value }: { value: unknown }) => (value === '' || value == null ? undefined : Number(value));

export const TIPOS_FILTRO_MOVIMIENTO = ['INGRESO', 'EGRESO', 'TRANSFERENCIA'] as const;
export const ESTADOS_FILTRO_MOVIMIENTO = ['BORRADOR', 'CONFIRMADO', 'ANULADO'] as const;

export class FiltroTesMovimientosDto {
  @ApiPropertyOptional()
  @IsOptional()
  @Transform(vacioEsUndefined)
  @IsUUID()
  cuentaId?: string;

  @ApiPropertyOptional({ enum: TIPOS_FILTRO_MOVIMIENTO })
  @IsOptional()
  @Transform(vacioEsUndefined)
  @IsIn(TIPOS_FILTRO_MOVIMIENTO)
  tipo?: (typeof TIPOS_FILTRO_MOVIMIENTO)[number];

  @ApiPropertyOptional({ enum: ESTADOS_FILTRO_MOVIMIENTO })
  @IsOptional()
  @Transform(vacioEsUndefined)
  @IsIn(ESTADOS_FILTRO_MOVIMIENTO)
  estado?: (typeof ESTADOS_FILTRO_MOVIMIENTO)[number];

  @ApiPropertyOptional({ example: '2026-05-01' })
  @IsOptional()
  @Transform(vacioEsUndefined)
  @IsDateString()
  fechaDesde?: string;

  @ApiPropertyOptional({ example: '2026-05-31' })
  @IsOptional()
  @Transform(vacioEsUndefined)
  @IsDateString()
  fechaHasta?: string;

  @ApiPropertyOptional({ description: 'Descripción, referencia, cuenta o importe' })
  @IsOptional()
  @Transform(vacioEsUndefined)
  @IsString()
  @MaxLength(100)
  search?: string;

  @ApiPropertyOptional({ default: 1 })
  @IsOptional()
  @Transform(numeroOUndefined)
  @IsInt()
  @Min(1)
  page?: number;

  @ApiPropertyOptional({ default: 20 })
  @IsOptional()
  @Transform(numeroOUndefined)
  @IsInt()
  @Min(1)
  @Max(100)
  limit?: number;
}

/** El Excel exporta el filtro entero: sin paginar. */
export class FiltroTesMovimientosExcelDto extends OmitType(FiltroTesMovimientosDto, ['page', 'limit'] as const) {}

/** Extracto de una cuenta. `cuentaId` se exige en el servicio, con código (`CUENTA_INVALIDA`); acá solo se valida el formato. */
export class FiltroExtractoDto {
  @ApiPropertyOptional()
  @IsOptional()
  @Transform(vacioEsUndefined)
  @IsUUID()
  cuentaId?: string;

  @ApiPropertyOptional({ example: '2026-05-01' })
  @IsOptional()
  @Transform(vacioEsUndefined)
  @IsDateString()
  fechaDesde?: string;

  @ApiPropertyOptional({ example: '2026-05-31' })
  @IsOptional()
  @Transform(vacioEsUndefined)
  @IsDateString()
  fechaHasta?: string;
}
