import { z } from 'zod';

import {
  type PerformanceReviewCoreFormQuestion,
  ReviewCommentableStatus,
  ReviewQuestionType,
} from 'src/pages/dashboard/performance/types';
import { type LokaliseTFunction } from 'src/utils/i18n';

import { buildCommentFieldName } from './constants';

/** Non-required fields don't need validation: any value is accepted. */
const optionalFieldSchema = z.any();

/** Required CHECKBOX: array with at least one entry. */
const requiredCheckboxSchema = (message: string) =>
  z.array(z.union([z.string(), z.number()])).min(1, message);

/** Required single-value answer (TEXT / MULTIPLE_CHOICE / RATING): non-empty string or number. */
const requiredAnswerSchema = (message: string) =>
  z.union([z.string(), z.number()]).refine(value => value !== '', message);

/** Required comment: non-empty string. */
const requiredCommentSchema = (message: string) => z.string().min(1, message);

const buildAnswerFieldSchema = (
  question: PerformanceReviewCoreFormQuestion,
  requiredMessage: string,
): z.ZodTypeAny => {
  if (!question.required) return optionalFieldSchema;

  if (question.type === ReviewQuestionType.CHECKBOX) {
    return requiredCheckboxSchema(requiredMessage);
  }

  return requiredAnswerSchema(requiredMessage);
};

const isCommentRequired = (
  status: PerformanceReviewCoreFormQuestion['commentableStatus'],
) => status === ReviewCommentableStatus.REQUIRED;

/**
 * Builds the Zod schema for the calibration form based on the questions returned
 * by the backend. Each question contributes:
 *   - an answer field (keyed by question id) with validation only when required.
 *   - a comment field (suffixed) with validation only when the question requires a comment.
 */
export const createCalibrationFormSchema = (
  questions: PerformanceReviewCoreFormQuestion[],
  t: LokaliseTFunction,
) => {
  const shape: Record<string, z.ZodTypeAny> = {};
  const requiredMessage = t('general:required_field');

  questions.forEach(question => {
    if (!question.id) return;

    shape[question.id] = buildAnswerFieldSchema(question, requiredMessage);

    if (isCommentRequired(question.commentableStatus)) {
      shape[buildCommentFieldName(question.id)] =
        requiredCommentSchema(requiredMessage);
    }
  });

  return z.object(shape);
};
