import { z } from 'zod';

import { type FileCardType } from '@material-hu/components/design-system/FileCard/types';

import { type TCustomFunction } from 'src/utils/i18n';

import {
  CertificateAlignment,
  CertificateColor,
  CertificateType,
} from '../constants';

import {
  CERTIFICATE_DESCRIPTION_MAX_LENGTH,
  CERTIFICATE_HEADING_TITLE_MAX_LENGTH,
  CERTIFICATE_MAX_LOGOS,
  CERTIFICATE_MAX_SIGNATURES,
  CERTIFICATE_NAME_MAX_LENGTH,
  CERTIFICATE_SUBTITLE_MAX_LENGTH,
} from './constants';
import { getCertificateFieldTextLength } from './utils';

const signatureSlotSchema = z.object({
  id: z.string(),
  file: z.array(z.custom<FileCardType>()),
  signerName: z.string(),
  signerTitle: z.string(),
});

const logoSlotSchema = z.object({
  id: z.string(),
  file: z.array(z.custom<FileCardType>()),
});

export const createCertificateCreateSchema = (t: TCustomFunction) =>
  z.object({
    type: z.nativeEnum(CertificateType),
    name: z
      .string()
      .min(1, t('validations:required_field'))
      .max(
        CERTIFICATE_NAME_MAX_LENGTH,
        t('validations:max_length', { count: CERTIFICATE_NAME_MAX_LENGTH }),
      ),
    title: z
      .string()
      .min(1, t('validations:required_field'))
      .max(
        CERTIFICATE_HEADING_TITLE_MAX_LENGTH,
        t('validations:max_length', {
          count: CERTIFICATE_HEADING_TITLE_MAX_LENGTH,
        }),
      ),
    subtitle: z
      .string()
      .refine(
        value =>
          getCertificateFieldTextLength(value, t) <=
          CERTIFICATE_SUBTITLE_MAX_LENGTH,
        t('validations:max_length', { count: CERTIFICATE_SUBTITLE_MAX_LENGTH }),
      ),
    description: z.string().refine(
      value =>
        getCertificateFieldTextLength(value, t) <=
        CERTIFICATE_DESCRIPTION_MAX_LENGTH,
      t('validations:max_length', {
        count: CERTIFICATE_DESCRIPTION_MAX_LENGTH,
      }),
    ),
    certificateSignaturesEnabled: z.boolean(),
    certificateLogosEnabled: z.boolean(),
    signatureSlots: z
      .array(signatureSlotSchema)
      .length(CERTIFICATE_MAX_SIGNATURES),
    logoSlots: z.array(logoSlotSchema).length(CERTIFICATE_MAX_LOGOS),
    alignment: z.nativeEnum(CertificateAlignment),
    color: z.nativeEnum(CertificateColor),
  });

export type CertificateCreateSchemaType = ReturnType<
  typeof createCertificateCreateSchema
>;
