// src/hooks/useAuth.ts
"use client";

import { useRouter } from "next/navigation";
import { useAuthStore } from "@/stores/auth";
import { api } from "@/lib/api";

export function useAuth() {
  const router = useRouter();
  const { user, token, setAuth, clearAuth } = useAuthStore();

  const login = async ({
    username,
    password,
  }: {
    username: string;
    password: string;
  }) => {
    try {
      const { data } = await api.post("/api/v1/app/auth/login", {
        username,
        password,
      });

      // Zustand store에 저장
      setAuth(data.user, data.token);

      // localStorage에도 저장
      localStorage.setItem("token", data.token);

      router.push("/dashboard/overview");
    } catch (error) {
      throw error;
    }
  };

  const logout = () => {
    clearAuth();
    localStorage.removeItem("token");
    router.push("/");
  };

  return { user, token, login, logout };
}