import { toTypedSchema } from "@vee-validate/zod";
import { z } from "zod";
import { WithdrawMethodEnum } from "@/api/enum";

export function createWithdrawSchema(t: (key: string, params?: any) => string, maxAmount: string) {
  return toTypedSchema(
    z.object({
      assetCode: z.string({ message: t("withdraw.validation.assetCodeRequired") }).min(1, t("withdraw.validation.assetCodeRequired")),
      amount: z
        .string({ message: t("withdraw.validation.amountRequired") })
        .min(1, t("withdraw.validation.amountRequired"))
        .refine(
          value => /^\d+(?:\.\d+)?$/.test(value),
          t("withdraw.validation.amountInvalid"),
        )
        .refine(
          (value) => {
            if (maxAmount === "0")
              return false;
            return Number.parseFloat(value) <= Number.parseFloat(maxAmount);
          },
          t("withdraw.validation.amountExceedsBalance"),
        )
        .refine(
          value => Number.parseFloat(value) > 0,
          t("withdraw.validation.amountTooSmall"),
        ),
      withdrawMethod: z.string({ message: t("withdraw.validation.methodRequired") }).min(1, t("withdraw.validation.methodRequired")),
      bankAccountId: z.string().optional(),
      chain: z.string().optional(),
      toAddress: z.string().optional(),
    })
      .refine(
        (data) => {
          if (data.withdrawMethod === WithdrawMethodEnum.BANK) {
            return !!data.bankAccountId;
          }
          return true;
        },
        {
          message: t("withdraw.validation.bankAccountRequired"),
          path: ["bankAccountId"],
        },
      )
      .refine(
        (data) => {
          if (data.withdrawMethod === WithdrawMethodEnum.CRYPTO) {
            return !!data.chain;
          }
          return true;
        },
        {
          message: t("withdraw.validation.chainRequired"),
          path: ["chain"],
        },
      )
      .refine(
        (data) => {
          if (data.withdrawMethod === WithdrawMethodEnum.CRYPTO) {
            return !!data.toAddress && data.toAddress.length >= 10;
          }
          return true;
        },
        {
          message: t("withdraw.validation.addressRequired"),
          path: ["toAddress"],
        },
      ),
  );
}
