import i18next from 'i18next';
import { type InferType, mixed, number, object, string } from 'yup';

import { CategoryTypes } from '../../../constants';
import { type CategoryType } from '../../../types';

export const createCategorySchema = object({
  categoryType: mixed<CategoryType>()
    .oneOf(Object.values(CategoryTypes))
    .default(CategoryTypes.PRINCIPAL),
  categoryName: string().trim().required(i18next.t('validations:required')),
  parentCategory: object({
    value: number(),
    label: string(),
    childrenCount: number(),
  })
    .nullable()
    .when('categoryType', {
      is: CategoryTypes.SUBCATEGORY,
      then: schema =>
        schema.test(
          'parent-categoryId-is-present',
          i18next.t('validations:required'),
          obj => obj?.value !== undefined && typeof obj.value === 'number',
        ),
      otherwise: schema => schema.optional(),
    }),
});

export type CreateCategoryFormValues = InferType<typeof createCategorySchema>;
