import { toTypedSchema } from "@vee-validate/yup";
import * as yup from "yup";
import { WithdrawMethodEnum } from "@/api/enum";

export function createWithdrawSchema(t: (key: string, params?: any) => string, maxAmount: string) {
  return toTypedSchema(
    yup.object({
      assetCode: yup.string().required(t("withdraw.validation.assetCodeRequired")),
      amount: yup
        .string()
        .required(t("withdraw.validation.amountRequired"))
        .test("is-number", t("withdraw.validation.amountInvalid"), (value) => {
          return /^\d+(?:\.\d+)?$/.test(value || "");
        })
        .test("max-amount", t("withdraw.validation.amountExceedsBalance"), (value) => {
          if (!value || maxAmount === "0")
            return false;
          return Number.parseFloat(value) <= Number.parseFloat(maxAmount);
        })
        .test("min-amount", t("withdraw.validation.amountTooSmall"), (value) => {
          if (!value)
            return false;
          return Number.parseFloat(value) > 0;
        }),
      withdrawMethod: yup.string().required(t("withdraw.validation.methodRequired")),
      bankAccountId: yup.string().when("withdrawMethod", {
        is: WithdrawMethodEnum.BANK,
        then: schema => schema.required(t("withdraw.validation.bankAccountRequired")),
        otherwise: schema => schema.optional(),
      }),
      chain: yup.string().when("withdrawMethod", {
        is: WithdrawMethodEnum.CRYPTO,
        then: schema => schema.required(t("withdraw.validation.chainRequired")),
        otherwise: schema => schema.optional(),
      }),
      toAddress: yup.string().when("withdrawMethod", {
        is: WithdrawMethodEnum.CRYPTO,
        then: schema => schema.required(t("withdraw.validation.addressRequired")).min(10, t("withdraw.validation.addressTooShort")),
        otherwise: schema => schema.optional(),
      }),
    }),
  );
}
