import { useI18n } from "vue-i18n";

export const useInputRules = () => {
  const { t } = useI18n();

  // Regex patterns
  const emailPattern =
    /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

  const cpfPattern = /^[0-9]{3}\.[0-9]{3}\.[0-9]{3}-[0-9]{2}$/;
  const cnpjPattern = /^[0-9]{2}\.[0-9]{3}\.[0-9]{3}\/[0-9]{4}-[0-9]{2}$/;
  const passwordPattern = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/;
  const cepPattern = /^[0-9]{5}-[0-9]{3}$/;

  const inputRules = {
    required: (value) => !!value || t("validation.rules.required"),
    requiredNumber: (value) => !isNaN(value) || t("validation.rules.required"),
    requiredHideMessage: (value) => !!value,

    min: (min) => (value) =>
      value?.length >= min ||
      `${t("validation.rules.min")} ${min} ${t("validation.rules.characters")}`,

    max: (max) => (value) =>
      value?.length <= max ||
      `${t("validation.rules.max")} ${max} ${t("validation.rules.characters")}`,

    minValue: (min) => (value) =>
      value >= min || `${t("validation.rules.min")} ${min}`,
    maxValue: (max) => (value) =>
      value <= max || `${t("validation.rules.max")} ${max}`,
    email: (value) =>
      !value || emailPattern.test(value) || t("validation.rules.email"),

    emails: (value) => {
      if (!value) return true;

      const emails = value.split(";").map((email) => email.trim());

      return (
        emails.every((email) => inputRules.email(email) === true) ||
        t("validation.rules.email")
      );
    },

    cpf: (value) =>
      !value || cpfPattern.test(value) || t("validation.rules.cpf"),
    cnpj: (value) =>
      !value || cnpjPattern.test(value) || t("validation.rules.cnpj"),

    samePassword: (otherValue) => (value) =>
      value === otherValue || t("validation.rules.same_password"),

    password: (value) =>
      !value || passwordPattern.test(value) || t("validation.rules.password"),

    cep: (value) => {
      return cepPattern.test(value) || t("validation.rules.cep");
    },
  };

  return {
    inputRules,
  };
};
