import axios from 'axios';

// Runtime API URL detection - works in the browser
const getApiBaseUrl = (): string => {
  const hostname = window.location.hostname;
  
  if (hostname === 'localhost' || hostname === '127.0.0.1') {
    // Local development
    return 'http://localhost:3001/api';
  } else {
    // Network access - use same host as frontend
    return `http://${hostname}:3001/api`;
  }
};

const API_BASE_URL = getApiBaseUrl();

console.log('🔗 API Base URL:', API_BASE_URL); // Debug log

const api = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});

// Recipe interfaces
export interface Recipe {
  id: number;
  recipeNumber: string;
  title: string;
  description?: string;
  category?: string;
  filePath?: string;
  preparation?: string;
  servings: number;
  ingredients?: string;
  instructions?: string;
  comment?: string;
  images?: RecipeImage[];
  ingredientsList?: Ingredient[];
}

export interface Ingredient {
  id: number;
  recipeNumber: string;
  ingredients: string;
}

export interface RecipeImage {
  id: number;
  recipeId: number;
  filePath: string;
}

export interface ApiResponse<T> {
  success: boolean;
  data: T;
  message?: string;
}

export interface PaginatedResponse<T> extends ApiResponse<T[]> {
  pagination: {
    page: number;
    limit: number;
    total: number;
    pages: number;
  };
}

// Recipe API methods
export const recipeApi = {
  // Get all recipes with pagination and search
  getRecipes: async (params?: {
    search?: string;
    category?: string;
    page?: number;
    limit?: number;
    sortBy?: string;
    sortOrder?: 'asc' | 'desc';
  }): Promise<PaginatedResponse<Recipe>> => {
    const response = await api.get('/recipes', { params });
    return response.data;
  },

  // Get single recipe by ID
  getRecipe: async (id: number): Promise<ApiResponse<Recipe>> => {
    const response = await api.get(`/recipes/${id}`);
    return response.data;
  },

  // Create new recipe
  createRecipe: async (recipe: Omit<Recipe, 'id'>): Promise<ApiResponse<Recipe>> => {
    const response = await api.post('/recipes', recipe);
    return response.data;
  },

  // Update recipe
  updateRecipe: async (id: number, recipe: Partial<Recipe>): Promise<ApiResponse<Recipe>> => {
    const response = await api.put(`/recipes/${id}`, recipe);
    return response.data;
  },

  // Delete recipe
  deleteRecipe: async (id: number): Promise<ApiResponse<null>> => {
    const response = await api.delete(`/recipes/${id}`);
    return response.data;
  },
};

// Ingredient API methods
export const ingredientApi = {
  getIngredients: async (params?: {
    search?: string;
    page?: number;
    limit?: number;
  }): Promise<PaginatedResponse<Ingredient>> => {
    const response = await api.get('/ingredients', { params });
    return response.data;
  },

  getIngredient: async (id: number): Promise<ApiResponse<Ingredient>> => {
    const response = await api.get(`/ingredients/${id}`);
    return response.data;
  },

  createIngredient: async (ingredient: Omit<Ingredient, 'id'>): Promise<ApiResponse<Ingredient>> => {
    const response = await api.post('/ingredients', ingredient);
    return response.data;
  },

  updateIngredient: async (id: number, ingredient: Partial<Ingredient>): Promise<ApiResponse<Ingredient>> => {
    const response = await api.put(`/ingredients/${id}`, ingredient);
    return response.data;
  },

  deleteIngredient: async (id: number): Promise<ApiResponse<null>> => {
    const response = await api.delete(`/ingredients/${id}`);
    return response.data;
  },
};

// Image API methods
export const imageApi = {
  getRecipeImages: async (recipeId: number): Promise<ApiResponse<RecipeImage[]>> => {
    const response = await api.get(`/images/recipe/${recipeId}`);
    return response.data;
  },

  getImageUrl: (imagePath: string): string => {
    return `${API_BASE_URL}/images/serve/${imagePath}`;
  },

  // Upload images for a recipe
  uploadImages: async (recipeId: number, files: File[], onProgress?: (progress: number) => void): Promise<ApiResponse<RecipeImage[]>> => {
    const formData = new FormData();
    files.forEach((file) => {
      formData.append('images', file);
    });

    const response = await api.post(`/images/upload/${recipeId}`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      onUploadProgress: (progressEvent) => {
        if (onProgress && progressEvent.total) {
          const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          onProgress(progress);
        }
      },
    });
    return response.data;
  },

  // Delete an image
  deleteImage: async (imageId: number): Promise<ApiResponse<null>> => {
    const response = await api.delete(`/images/${imageId}`);
    return response.data;
  },
};

// Health check
export const healthApi = {
  check: async (): Promise<ApiResponse<{ status: string; timestamp: string }>> => {
    const response = await api.get('/health');
    return response.data;
  },
};

export default api;