import * as Yup from 'yup';
import { WarehouseType } from '@/types/api/master-data/warehouse';

const TYPE_VALUES = ['AREA', 'LOKASI', 'KANDANG'] as const;

export const WarehouseFormSchema = Yup.object({
  name: Yup.string().required('Nama wajib diisi!'),

  type: Yup.string<WarehouseType>()
    .oneOf(TYPE_VALUES)
    .required('Tipe wajib diisi!'),

  areaId: Yup.number()
    .transform((v, orig) =>
      orig === '' || orig === 0 || Number.isNaN(v) ? undefined : v
    )
    .when('type', {
      is: (t: WarehouseType | undefined) =>
        t === 'AREA' || t === 'LOKASI' || t === 'KANDANG',
      then: (s) => s.min(1, 'Area wajib diisi!').required('Area wajib diisi!'),
      otherwise: (s) => s.notRequired(),
    }),
  area: Yup.object({
    value: Yup.number().min(1).required(),
    label: Yup.string().required(),
  })
    .nullable()
    .when('type', {
      is: (t: WarehouseType | undefined) =>
        t === 'AREA' || t === 'LOKASI' || t === 'KANDANG',
      then: (s) => s.notRequired(),
      otherwise: (s) => s.notRequired(),
    }),

  locationId: Yup.number()
    .transform((v, orig) =>
      orig === '' || orig === 0 || Number.isNaN(v) ? undefined : v
    )
    .when('type', {
      is: (t: WarehouseType | undefined) => t === 'LOKASI' || t === 'KANDANG',
      then: (s) =>
        s.min(1, 'Lokasi wajib diisi!').required('Lokasi wajib diisi!'),
      otherwise: (s) => s.notRequired(),
    }),
  location: Yup.object({
    value: Yup.number().min(1).required(),
    label: Yup.string().required(),
  })
    .nullable()
    .when('type', {
      is: (t: WarehouseType | undefined) => t === 'LOKASI' || t === 'KANDANG',
      then: (s) => s.notRequired(),
      otherwise: (s) => s.notRequired(),
    }),

  kandangId: Yup.number()
    .transform((v, orig) =>
      orig === '' || orig === 0 || Number.isNaN(v) ? undefined : v
    )
    .when('type', {
      is: (t: WarehouseType | undefined) => t === 'KANDANG',
      then: (s) =>
        s.min(1, 'Kandang wajib diisi!').required('Kandang wajib diisi!'),
      otherwise: (s) => s.notRequired(),
    }),
  kandang: Yup.object({
    value: Yup.number().min(1).required(),
    label: Yup.string().required(),
  })
    .nullable()
    .when('type', {
      is: (t: WarehouseType | undefined) => t === 'KANDANG',
      then: (s) => s.notRequired(),
      otherwise: (s) => s.notRequired(),
    }),
});

export const UpdateWarehouseFormSchema = WarehouseFormSchema;

export type WarehouseFormValues = Yup.InferType<typeof WarehouseFormSchema>;
