import { useState, useEffect, createContext, useContext } from "react";
import { api } from "../services/api";

export interface AuthUser {
  id: number;
  username: string;
  isAdmin: boolean;
  isFounder: boolean;
  setupComplete: boolean;
  giteaUsername: string | null;
  giteaInstanceUrl: string | null;
  giteaPatSet: boolean;
  awsAccessKeyId: string | null;
  awsRegion: string | null;
  awsConfigured: boolean;
}

interface AuthContextType {
  user: AuthUser | null;
  loading: boolean;
  refresh: () => Promise<void>;
}

export const AuthContext = createContext<AuthContextType>({
  user: null,
  loading: true,
  refresh: async () => {},
});

export function useAuth() {
  return useContext(AuthContext);
}

export function useAuthProvider(): AuthContextType {
  const [user, setUser] = useState<AuthUser | null>(null);
  const [loading, setLoading] = useState(true);

  const refresh = async () => {
    const res = await api.auth.me();
    if (res.ok && res.data) {
      setUser(res.data as AuthUser);
    } else {
      setUser(null);
    }
    setLoading(false);
  };

  useEffect(() => {
    refresh();
  }, []);

  return { user, loading, refresh };
}
