import {
  IsEnum,
  IsBoolean,
  IsString,
  IsOptional,
  IsArray,
  IsUUID,
  IsNumber,
  IsPositive,
  IsDate,
  ValidateNested,
} from 'class-validator'
import { Type, Transform } from 'class-transformer'
import { TransactionStatus } from 'generated/prisma/client'

function parseIndonesianDate(value: string | Date): Date {
  if (!value) return new Date()
  if (value instanceof Date) return value

  const months: Record<string, number> = {
    Januari: 0,
    Februari: 1,
    Maret: 2,
    April: 3,
    Mei: 4,
    Juni: 5,
    Juli: 6,
    Agustus: 7,
    September: 8,
    Oktober: 9,
    November: 10,
    Desember: 11,
  }

  if (!value.includes(',')) return new Date(value)

  const [datePart, timePart] = value.split(', ')
  const [day, monthName, year] = datePart.split(' ')
  const [hour, minute] = timePart.split(':')

  return new Date(
    Number(year),
    months[monthName],
    Number(day),
    Number(hour),
    Number(minute)
  )
}

export class UpdateTransactionItemDto {

  @IsUUID()
  id: string

  @IsOptional()
  @IsString()
  itemCode?: string

  @IsOptional()
  @IsString()
  itemTypeId?: string

  @IsOptional()
  @Type(() => Number)
  @IsNumber()
  @IsPositive()
  grossWeight?: number

  @IsOptional()
  @Type(() => Number)
  @IsNumber()
  @IsPositive()
  netWeight?: number

  @IsOptional()
  @IsString()
  caratId?: string

  @IsOptional()
  @Type(() => Number)
  @IsNumber()
  @IsPositive()
  pricePerGram?: number

  @IsOptional()
  @Transform(({ value }) => parseIndonesianDate(value))
  @IsDate()
  pricePerGramAt?: Date

  @IsOptional()
  @Type(() => Number)
  @IsNumber()
  @IsPositive()
  purityPercent?: number

  @IsOptional()
  @IsArray()
  @IsUUID('4', { each: true })
  tempPhotoIds?: string[]
}

export class UpdateTransactionDto {

  @IsOptional()
  @IsEnum(TransactionStatus)
  status?: TransactionStatus

  @IsOptional()
  @Type(() => Number)
  @IsNumber()
  totalGrossWeight?: number

  @IsOptional()
  @Type(() => Number)
  @IsNumber()
  totalNetWeight?: number

  @IsOptional()
  @Type(() => Number)
  @IsNumber()
  totalAmount?: number

  @IsOptional()
  @IsUUID()
  bankId?: string

  @IsOptional()
  @IsString()
  bankAccountNo?: string

  @IsOptional()
  @IsString()
  bankAccountName?: string

  @IsOptional()
  @IsString()
  customerId?: string

  @IsOptional()
  @IsString()
  referralSource?: string

  @IsOptional()
  @IsBoolean()
  knowsFounder?: boolean

  @IsOptional()
  @ValidateNested({ each: true })
  @Type(() => UpdateTransactionItemDto)
  items?: UpdateTransactionItemDto[]
}