import { z } from 'zod'
import { PersonAddressSchema } from './person-address.schema'

const PersonAddressRelativeSchema = z
  .object({
    isSameAddress: z
      .union([z.literal('1'), z.literal('0'), z.boolean()])
      .default('1')
      .transform((val) => {
        if (typeof val === 'boolean') return val ? '1' : '0'
        return val
      }),
  })
  .merge(PersonAddressSchema.partial())
  .superRefine((data, ctx) => {
    const isSameAddress = data.isSameAddress

    // Jika alamat tidak sama ('0'), maka semua field address wajib diisi
    if (isSameAddress === '0') {
      const requiredFields = [
        'province_code',
        'regency_code',
        'district_code',
        'village_code',
        'postalRegion_code',
        'address',
      ]

      requiredFields.forEach((field) => {
        if (!data[field as keyof typeof data]) {
          ctx.addIssue({
            code: z.ZodIssueCode.custom,
            message: getRequiredMessage(field),
            path: [field],
          })
        }
      })
    }
  })
  .transform((data) => ({
    ...data,
    isSameAddress: data.isSameAddress === '1',
  }))

function getRequiredMessage(field: string): string {
  const messages: Record<string, string> = {
    province_code: 'Mohon pilih provinsi',
    regency_code: 'Mohon pilih kabupaten/kota',
    district_code: 'Mohon pilih kecamatan',
    village_code: 'Mohon pilih kelurahan',
    postalRegion_code: 'Mohon lengkapi kode pos',
    address: 'Mohon lengkapi alamat',
  }
  return messages[field] || `${field} wajib diisi`
}

type PersonAddressRelativeFormData = z.infer<typeof PersonAddressRelativeSchema>

export { PersonAddressRelativeSchema }
export type { PersonAddressRelativeFormData }
