import type { PhoneCountry } from "./type";
import { toTypedSchema } from "@vee-validate/yup";
import { emailOTPClient, phoneNumberClient, usernameClient } from "better-auth/client/plugins";
import { createAuthClient } from "better-auth/vue";
import * as yup from "yup";
import CircleFlagsCnHk from "~icons/circle-flags/cn-hk";
import CircleFlagsEnUs from "~icons/circle-flags/en-us";
import CircleFlagsTw from "~icons/circle-flags/tw";
import CircleFlagsZh from "~icons/circle-flags/zh";
import { i18n } from "@/locales";

const baseURL = import.meta.env.DEV ? window.location.origin : import.meta.env.VITE_API_URL;

export const authClient = createAuthClient({
  baseURL,
  fetchOptions: {
    credentials: "include",
    auth: {
      type: "Bearer",
      token: () => localStorage.getItem("user-token") || "",
    },
  },
  plugins: [emailOTPClient(), phoneNumberClient(), usernameClient()],
});

export const emailSchema = toTypedSchema(yup.object({
  email: yup
    .string()
    .required(i18n.global.t("auth.login.validation.emailRequired"))
    .email(i18n.global.t("auth.login.validation.emailInvalid")),
  otp: yup
    .string()
    .required(i18n.global.t("auth.login.validation.otpRequired"))
    .matches(/^\d{6}$/, i18n.global.t("auth.login.validation.otpInvalid")),
}));

export const countries: PhoneCountry[] = [
  {
    code: "CN",
    dialCode: "+86",
    name: "中国大陆",
    pattern: /^1[3-9]\d{9}$/,
    maxLength: 11,
    placeholder: "13800138000",
    icon: CircleFlagsZh,
  },
  {
    code: "HK",
    dialCode: "+852",
    name: "中国香港",
    pattern: /^[5-9]\d{7}$/,
    maxLength: 8,
    placeholder: "51234567",
    icon: CircleFlagsCnHk,
  },
  {
    code: "TW",
    dialCode: "+886",
    name: "中国台湾",
    pattern: /^9\d{8}$/,
    maxLength: 9,
    placeholder: "912345678",
    icon: CircleFlagsTw,
  },
  {
    code: "US",
    dialCode: "+1",
    name: "美国",
    pattern: /^\d{10}$/,
    maxLength: 10,
    placeholder: "2025550123",
    icon: CircleFlagsEnUs,
  },
];
