import { API_BASE_URL } from "../constants";
import type { SteamUser, VoteStatusResponse, MapOption } from "../types";

export const authService = {
  async checkUser(): Promise<{ user: SteamUser } | null> {
    try {
      const response = await fetch(`${API_BASE_URL}/auth/user`, {
        credentials: "include",
      });
      
      if (response.ok) {
        return await response.json();
      }
      return null;
    } catch (error) {
      console.error("Auth check failed:", error);
      return null;
    }
  },

  async logout(): Promise<void> {
    try {
      await fetch(`${API_BASE_URL}/auth/logout`, {
        credentials: "include",
      });
    } catch (error) {
      console.error("Logout failed:", error);
      throw error;
    }
  },

  getSteamLoginUrl(): string {
    return `${API_BASE_URL}/auth/steam`;
  }
};

export const voteService = {
  async checkVoteStatus(): Promise<VoteStatusResponse> {
    try {
      const response = await fetch(`${API_BASE_URL}/api/vote-status`, {
        credentials: "include",
      });

      if (response.ok) {
        return await response.json();
      }
      throw new Error("Failed to check vote status");
    } catch (error) {
      console.error("Failed to check vote status:", error);
      throw error;
    }
  },

  async submitVote(vote: MapOption[]): Promise<{ success: boolean; message: string; user: string }> {
    try {
      const response = await fetch(`${API_BASE_URL}/api/submit-vote`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        credentials: "include",
        body: JSON.stringify({ vote }),
      });

      if (response.ok) {
        return await response.json();
      } else {
        const error = await response.json();
        throw new Error(error.error);
      }
    } catch (error) {
      console.error("Failed to submit vote:", error);
      throw error;
    }
  }
};
