import {
  IsOptional,
  IsString,
  IsNumber,
  Min,
  IsIn,
  IsEnum,
  IsDateString,
  IsArray,
} from 'class-validator';
import { Type, Transform } from 'class-transformer';
import { ApiPropertyOptional } from '@nestjs/swagger';
import { OrderStatus } from '../interface/order.interface';
import { PaymentStatusEnum } from '../../payments/interface/payment';

const sortOrderOptions = ['asc', 'desc'] as const;
type SortOrder = (typeof sortOrderOptions)[number];

export class FindOrdersDto {
  @ApiPropertyOptional({ default: 1, minimum: 1 })
  @IsOptional()
  @Type(() => Number)
  @IsNumber()
  @Min(1)
  page: number = 1;

  @ApiPropertyOptional({ default: 10, minimum: 1 })
  @IsOptional()
  @Type(() => Number)
  @IsNumber()
  @Min(1)
  limit: number = 10;

  /**
   * ?statuses=paid,confirmed
   * ?statuses=paid&statuses=confirmed
   */
  @ApiPropertyOptional({
    description: 'Filter by order statuses',
    enum: OrderStatus,
    isArray: true,
  })
  @IsOptional()
  @Transform(({ value }) =>
    Array.isArray(value) ? value : value?.split(',')
  )
  @IsArray()
  @IsEnum(OrderStatus, { each: true })
  statuses?: OrderStatus[];

  @ApiPropertyOptional({ enum: PaymentStatusEnum })
  @IsOptional()
  @IsEnum(PaymentStatusEnum)
  paymentStatus?: PaymentStatusEnum;

  @ApiPropertyOptional()
  @IsOptional()
  @IsString()
  search?: string;

  @ApiPropertyOptional({ format: 'date-time' })
  @IsOptional()
  @IsDateString()
  startDate?: string;

  @ApiPropertyOptional({ format: 'date-time' })
  @IsOptional()
  @IsDateString()
  endDate?: string;

  @ApiPropertyOptional({ default: 'createdAt' })
  @IsOptional()
  @IsString()
  orderBy: string = 'createdAt';

  @ApiPropertyOptional({
    enum: sortOrderOptions,
    default: 'desc',
  })
  @IsOptional()
  @IsIn(sortOrderOptions)
  order: SortOrder = 'desc';
}
