import type { GenericResponse } from "~/types";
import type { Customer } from "~/types/user";

export const useUserStore = defineStore("userStore", () => {
  const store = useStore();

  const fullUserData = ref<Customer | null>(null);
  const isLogged = ref<boolean>(true);
  const user = ref<string | null>(null);

  async function checkIsLogged() {
    try {
      const { data } = await useMyFetch<
        GenericResponse<{ loggedin: boolean } | Customer>
      >(`/api/public/user`, {
        headers: {
          "Content-Type": "application/json",
        },
        onErrorOccured: async (_, status) => {
          throw createError({
            statusCode: status,
            statusMessage: `HTTP error: ${status}`,
          });
        },
      });

      if ("loggedin" in data && data.loggedin === true) {
        isLogged.value = true;
        user.value = null;
        fullUserData.value = null;
      } else if ("first_name" in data && "last_name" in data) {
        isLogged.value = true;
        user.value = `${data.first_name} ${data.last_name}`;
        fullUserData.value = data as Customer;
      } else {
        isLogged.value = false;
        user.value = null;
        fullUserData.value = null;
      }
    } catch (error) {
      console.error("checkIsLogged error:", error);
    }
  }

  // login
  const email = ref();
  const password = ref();
  const vLogin = ref<boolean>(true);
  const vCodeVerify = ref<boolean>(false);
  const vCode = ref<number | null>(null);
  const vEmail = ref<string>("");
  async function logIn() {
    try {
      const data = await useMyFetch<GenericResponse<object>>(
        `/api/public/user/session/start`,
        {
          method: "POST",
          body: JSON.stringify({
            mail: email.value,
            password: password.value,
          }),
          headers: {
            "Content-Type": "application/json",
          },
          onErrorOccured: (_, status) => {
            throw new Error(`HTTP error: ${status}`);
          },
        }
      );

      if (data.status === 200 || data.status === 201) {
        console.log(vCodeVerify.value);

        // $toast.success("Address successfully added", {
        //   autoClose: 5000,
        //   dangerouslyHTMLString: true,
        // });
        vLogin.value = false;
        vCodeVerify.value = true;
      }
      // else {
      //   $toast.error("Failed to add address. Please try again.", {
      //     autoClose: 5000,
      //     dangerouslyHTMLString: true,
      //   });
      // }

      store.minValue = data;
    } catch (error) {
      console.error("getList error:", error);
    }
  }
  return {
    isLogged,
    user,
    fullUserData,
    vCodeVerify,
    vCode,
    vEmail,
    email,
    password,
    logIn,
    checkIsLogged,
  };
});
