import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { ArrayMaxSize, IsArray, IsIn, IsOptional, IsString, MaxLength } from 'class-validator';
import {
  SUPERADMIN_CASE_PRIORITIES,
  SUPERADMIN_CASE_STATUSES,
} from '../schemas/superadmin-case.schema';

const toStringArray = ({ value }: { value: unknown }): string[] => {
  if (Array.isArray(value)) {
    return value
      .map((entry) => (typeof entry === 'string' ? entry.trim() : ''))
      .filter(Boolean);
  }

  if (typeof value === 'string') {
    return value
      .split(',')
      .map((entry) => entry.trim())
      .filter(Boolean);
  }

  return [];
};

export class CreateSuperAdminCaseDto {
  @ApiProperty()
  @IsString()
  @MaxLength(120)
  title!: string;

  @ApiPropertyOptional()
  @IsOptional()
  @IsString()
  @MaxLength(2000)
  description?: string;

  @ApiProperty()
  @IsString()
  @MaxLength(80)
  caseType!: string;

  @ApiProperty()
  @IsString()
  @MaxLength(80)
  resourceType!: string;

  @ApiPropertyOptional()
  @IsOptional()
  @IsString()
  @MaxLength(120)
  resourceId?: string;

  @ApiPropertyOptional({ enum: SUPERADMIN_CASE_STATUSES })
  @IsOptional()
  @IsIn(SUPERADMIN_CASE_STATUSES)
  status?: (typeof SUPERADMIN_CASE_STATUSES)[number];

  @ApiPropertyOptional({ enum: SUPERADMIN_CASE_PRIORITIES })
  @IsOptional()
  @IsIn(SUPERADMIN_CASE_PRIORITIES)
  priority?: (typeof SUPERADMIN_CASE_PRIORITIES)[number];

  @ApiPropertyOptional()
  @IsOptional()
  @IsString()
  @MaxLength(160)
  assignedTo?: string;

  @ApiPropertyOptional({ type: [String] })
  @IsOptional()
  @Transform(toStringArray)
  @IsArray()
  @ArrayMaxSize(12)
  @IsString({ each: true })
  tags?: string[];

  @ApiPropertyOptional()
  @IsOptional()
  @IsString()
  @MaxLength(1200)
  note?: string;
}
