import { createContext, useContext, useState } from 'react';
import api from '@/services/api';

type AuthContextType = {
	user: any;
	token: string | null;
	login: (username: string, password: string) => Promise<void>;
	logout: () => void;
};

const AuthContext = createContext<AuthContextType | null>(null);

export function AuthProvider({ children }: { children: React.ReactNode }) {
	const [token, setToken] = useState<string | null>(localStorage.getItem('token'));

	const [user, setUser] = useState(null);

	async function login(username: string, password: string) {
		const response = await api.post('/auth/login', {
			username,
			password,
		});

		const token = response.data.token;

		localStorage.setItem('token', token);

		setToken(token);
	}

	function logout() {
		localStorage.removeItem('token');

		setToken(null);
		setUser(null);
	}

	return (
		<AuthContext.Provider
			value={{
				user,
				token,
				login,
				logout,
			}}
		>
			{children}
		</AuthContext.Provider>
	);
}

export function useAuth() {
	const context = useContext(AuthContext);

	if (!context) {
		throw new Error('useAuth must be used inside AuthProvider');
	}

	return context;
}
