import { authApiClient } from "./authApiClients";
import { safeLocalStorage } from "@/lib/utils";

interface ApiError extends Error {
  response?: any;
}

export const registerUser = async (
  data: {
    username: string;
    email: string;
    password: string;
    first_name: string;
    last_name: string;
    role: string;
  }
) => {
  console.log("Registering user with data:", data);
  try {
    const response = await authApiClient.post(
      "/api/auth/register",
      data
    );
    return response.data;
  } catch (error: any) {
    console.error("Error registering user:", error.response?.data || error.message);
    
    // Create a proper error object that preserves the original response
    const enhancedError: ApiError = new Error(
      error.response?.data?.message || error.response?.data?.error || "Failed to register user. Please try again."
    );
    enhancedError.response = error.response;
    throw enhancedError;
  }
};

export const loginUser = async (email: string, password: string) => {
  console.log("Logging in user with email:", email);
  try {
    const response = await authApiClient.post(
      "/api/auth/login",
      { email, password }
    );
    return response.data;
  } catch (error: any) {
    console.error("Error logging in user:", error.response?.data || error.message);
    
    // Create a proper error object that preserves the original response
    const enhancedError: ApiError = new Error(
      error.response?.data?.message || error.response?.data?.error || "Failed to log in. Please check your credentials."
    );
    enhancedError.response = error.response;
    throw enhancedError;
  }
}

export const logoutUser = async () => {
  console.log("Logging out user");
  try {
    const refreshToken = safeLocalStorage.getItem('refreshToken');
    if (refreshToken) {
      await authApiClient.post("/api/auth/logout", { refreshToken });
    }
    return { success: true, message: "Logged out successfully" };
  } catch (error: any) {
    console.error("Error logging out user:", error.response?.data || error.message);
    
    // Create a proper error object that preserves the original response
    const enhancedError: ApiError = new Error(
      error.response?.data?.message || error.response?.data?.error || "Failed to log out. Please try again."
    );
    enhancedError.response = error.response;
    throw enhancedError;
  }
}