import { create } from "zustand";
import { api } from "../api/client";

interface AuthState {
  username: string | null;
  loading: boolean;
  error: string | null;
  login: (username: string, password: string) => Promise<boolean>;
  logout: () => Promise<void>;
  check: () => Promise<void>;
}

export const useAuthStore = create<AuthState>((set) => ({
  username: null,
  loading: false,
  error: null,
  login: async (username, password) => {
    set({ loading: true, error: null });
    try {
      const response = await api.post("/api/auth/login", { username, password });
      if (response.data?.token) {
        localStorage.setItem("qbuffer_token", response.data.token);
      }
      set({ username: response.data.username, loading: false });
      return true;
    } catch (error) {
      set({ error: "Login failed", loading: false });
      return false;
    }
  },
  logout: async () => {
    await api.post("/api/auth/logout");
    localStorage.removeItem("qbuffer_token");
    set({ username: null });
  },
  check: async () => {
    try {
      const response = await api.get("/api/auth/me");
      set({ username: response.data.username ?? "session" });
    } catch (error) {
      localStorage.removeItem("qbuffer_token");
      set({ username: null });
    }
  },
}));
