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

interface ApiResponse {
  data?: {
    message?: string;
    error?: string;
  };
}

interface ApiError extends Error {
  response?: ApiResponse;
}

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 {
    // Using centralized backend URL
    const response = await fetch(`${BACKEND_URL}/api/auth/register`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      credentials: 'include',
      body: JSON.stringify(data)
    });
    
    const responseData = await response.json();
    
    if (!response.ok) {
      // Extract error message from server response
      const errorMessage = responseData?.message || responseData?.error || responseData?.detail || `Registration failed (${response.status})`;
      throw new Error(errorMessage);
    }
    
    return responseData;
  } catch (error: unknown) {
    console.error("Error registering user:", error);
    
    // If it's already our enhanced error with proper message, re-throw it
    if (error instanceof Error) {
      throw error;
    }
    
    // Create a proper error object for unexpected errors
    const enhancedError: ApiError = new Error(
      "Failed to register user. Please try again."
    );
    throw enhancedError;
  }
};

export const loginUser = async (email: string, password: string) => {
  console.log("Logging in user with email:", email);
  try {
    // Using centralized backend URL
    const response = await fetch(`${BACKEND_URL}/api/auth/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      credentials: 'include',
      body: JSON.stringify({ email, password })
    });
    
    const data = await response.json();
    
    if (!response.ok) {
      // Extract error message from server response
      const errorMessage = data?.message || data?.error || data?.detail || `Login failed (${response.status})`;
      throw new Error(errorMessage);
    }
    
    return data;
  } catch (error: unknown) {
    console.error("Error logging in user:", error);
    
    // If it's already our enhanced error with proper message, re-throw it
    if (error instanceof Error) {
      throw error;
    }
    
    // Create a proper error object for unexpected errors
    const enhancedError: ApiError = new Error(
      "Failed to log in. Please check your credentials."
    );
    throw enhancedError;
  }
}

export const logoutUser = async () => {
  console.log("Logging out user");
  try {
    const refreshToken = safeLocalStorage.getItem('refreshToken');
    if (refreshToken) {
      // Using centralized backend URL
      const response = await fetch(`${BACKEND_URL}/api/auth/logout`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({ refreshToken })
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
    }
    return { success: true, message: "Logged out successfully" };
  } catch (error: unknown) {
    console.error("Error logging out user:", error);
    
    // Create a proper error object
    const enhancedError: ApiError = new Error(
      error instanceof Error ? error.message : "Failed to log out. Please try again."
    );
    throw enhancedError;
  }
}