import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsDateString, IsIn, IsOptional, registerDecorator, ValidationArguments, ValidationOptions } from 'class-validator';

function MaxDateRangeDays(maxDays: number, validationOptions?: ValidationOptions) {
  return function (object: object, propertyName: string) {
    registerDecorator({
      name: 'maxDateRangeDays',
      target: (object as { constructor: new (...args: unknown[]) => unknown }).constructor,
      propertyName,
      options: validationOptions,
      validator: {
        validate(_value: unknown, args: ValidationArguments) {
          const dto = args.object as RevenueStatsDto;
          if (!dto.startDate || !dto.endDate) return true;
          const start = new Date(dto.startDate);
          const end = new Date(dto.endDate);
          const diffMs = end.getTime() - start.getTime();
          const diffDays = diffMs / (1000 * 60 * 60 * 24);
          return diffDays >= 0 && diffDays <= maxDays;
        },
        defaultMessage(args: ValidationArguments) {
          return `Date range must not exceed ${(args.constraints as number[])[0]} days`;
        },
      },
      constraints: [maxDays],
    });
  };
}

export class RevenueStatsDto {
  @ApiProperty({ description: 'Start date (ISO 8601)', example: '2025-01-01' })
  @IsDateString()
  startDate!: string;

  @ApiProperty({ description: 'End date (ISO 8601)', example: '2025-12-31' })
  @IsDateString()
  @MaxDateRangeDays(366, { message: 'Date range must not exceed 366 days' })
  endDate!: string;

  @ApiPropertyOptional({ description: 'Group results by day or month', enum: ['day', 'month'], default: 'month' })
  @IsOptional()
  @IsIn(['day', 'month'])
  groupBy?: 'day' | 'month';
}
