// frontend/context/AuthContext.jsx
'use client';

import { createContext, useState, useContext, useEffect } from 'react';
import { api } from '@/lib/api';
import { cookieDriver } from '@/app/_auth/drivers/cookieDriver';

const AuthContext = createContext(null);
const COOKIE_NAME = "access_token";

export function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const initializeAuth = async () => {
      const token = cookieDriver.get(COOKIE_NAME); 
      if (token) {
        try {
          api.defaults.headers.Authorization = `Bearer ${token}`;
          const response = await api.get('/auth/me');
          setUser(response.data.user || response.data);
        } catch (error) {
          cookieDriver.remove(COOKIE_NAME);
          delete api.defaults.headers.Authorization;
        }
      }
      setLoading(false);
    };
    initializeAuth();
  }, []);

  const login = async (credentials) => {
    const response = await api.post('/auth/login', credentials);
    const { token, user } = response.data;
    cookieDriver.set(COOKIE_NAME, token, { expires: 7 });
    api.defaults.headers.Authorization = `Bearer ${token}`;
    setUser(user);
    return user;
  };

  const logout = () => {
    cookieDriver.remove(COOKIE_NAME);
    delete api.defaults.headers.Authorization;
    setUser(null);
    window.location.href = '/login';
  };

  return (
    <AuthContext.Provider value={{ user, isAuthenticated: !!user, loading, login, logout }}>
      {!loading && children}
    </AuthContext.Provider>
  );
}

export const useAuth = () => {
  return useContext(AuthContext);
};