import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Transform, Type } from 'class-transformer';
import {
  IsDateString,
  IsInt,
  IsOptional,
  IsString,
  Matches,
  Min,
} from 'class-validator';

function emptyTextToUndefined({ value }: { value: unknown }) {
  if (typeof value !== 'string') return value;

  const trimmed = value.trim();
  return trimmed || undefined;
}

export class UpsertMyProgressReportIssueDto {
  @ApiProperty({ example: 4 })
  @Type(() => Number)
  @IsInt()
  @Min(1)
  issueStatusId!: number;

  @ApiPropertyOptional({ example: '80% completed' })
  @Transform(emptyTextToUndefined)
  @IsOptional()
  @IsString()
  indicators?: string;

  @ApiPropertyOptional({ example: 'Installed the required equipment' })
  @Transform(emptyTextToUndefined)
  @IsOptional()
  @IsString()
  progressSolution?: string;

  @ApiPropertyOptional({ example: 'Budget was delayed' })
  @Transform(emptyTextToUndefined)
  @IsOptional()
  @IsString()
  implementationChallenges?: string;

  @ApiPropertyOptional({ example: 'Need technical support' })
  @Transform(emptyTextToUndefined)
  @IsOptional()
  @IsString()
  requests?: string;

  @ApiPropertyOptional({ example: 'Inspection report' })
  @Transform(emptyTextToUndefined)
  @IsOptional()
  @IsString()
  sourceOfVerification?: string;

  // Edited via a rich-text EditorBox (it submits HTML, not a bare URL), so this
  // is validated as free text like sourceOfVerification rather than @IsUrl.
  @ApiPropertyOptional({ example: 'Ministry progress-report page' })
  @Transform(emptyTextToUndefined)
  @IsOptional()
  @IsString()
  linkToVerificationSource?: string;

  @ApiPropertyOptional({ example: 'Complete the remaining work' })
  @Transform(emptyTextToUndefined)
  @IsOptional()
  @IsString()
  nextStep?: string;

  @ApiPropertyOptional({
    example: '2026-07-24',
    description: 'Optional solution date in YYYY-MM-DD format.',
  })
  @Transform(emptyTextToUndefined)
  @IsOptional()
  @Matches(/^\d{4}-\d{2}-\d{2}$/)
  @IsDateString()
  dateOfIssueSolution?: string;
}
