import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { useRouter } from "vue-router";

export const useAuthStore = defineStore("auth", () => {
  // State
  const token = ref(localStorage.getItem("token") || "");
  const user = ref(JSON.parse(localStorage.getItem("user") || "null"));
  const loading = ref(false);
  const error = ref("");

  // Getters
  const isAuthenticated = computed(() => Boolean(token.value));
  const userRole = computed(() => user.value?.role || "guest");

  // API URL - update with your actual backend URL
  const apiBaseUrl = "http://localhost:3000/api";

  // Actions
  async function login(username: string, password: string) {
    loading.value = true;
    error.value = "";

    try {
      const response = await fetch(`${apiBaseUrl}/auth/login`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ username, password }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.message || "Login failed");
      }

      // Store auth data in localStorage
      localStorage.setItem("token", data.token);
      localStorage.setItem(
        "user",
        JSON.stringify({
          id: data.userId,
          username: data.username,
          role: data.role || "user",
        }),
      );

      // Update state
      token.value = data.token;
      user.value = {
        id: data.userId,
        username: data.username,
        role: data.role || "user",
      };

      return true;
    } catch (err: any) {
      error.value = err.message || "Something went wrong";
      return false;
    } finally {
      loading.value = false;
    }
  }

  async function register(username: string, password: string, email: string) {
    loading.value = true;
    error.value = "";

    try {
      const response = await fetch(`${apiBaseUrl}/auth/register`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ username, password, email }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.message || "Registration failed");
      }

      return true;
    } catch (err: any) {
      error.value = err.message || "Something went wrong";
      return false;
    } finally {
      loading.value = false;
    }
  }

  function logout() {
    // Clear state and localStorage
    token.value = "";
    user.value = null;
    localStorage.removeItem("token");
    localStorage.removeItem("user");

    // Use router to redirect to login page
    const router = useRouter();
    router.push("/login");
  }

  return {
    // State
    token,
    user,
    loading,
    error,

    // Getters
    isAuthenticated,
    userRole,

    // Actions
    login,
    register,
    logout,
  };
});
