import axios from 'axios';
import {
  FunctionDefinition,
  FunctionExecution,
  CreateFunctionRequest,
  UpdateFunctionRequest,
  ExecuteFunctionRequest,
  ExecuteFunctionResponse,
  RuntimeInfo,
} from '../types';

const API_BASE_URL = process.env.NODE_ENV === 'production' 
  ? '/api/faas/api' 
  : 'http://localhost:8083/api';

const api = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
    'X-User-Email': 'admin@example.com', // Mock auth header
  },
});

// Add response interceptor for error handling
api.interceptors.response.use(
  (response) => response,
  (error) => {
    console.error('API Error:', error.response?.data || error.message);
    return Promise.reject(error);
  }
);

export const functionApi = {
  // Function management
  list: (appId?: string, limit = 50, offset = 0) =>
    api.get<{ functions: FunctionDefinition[] }>('/functions', {
      params: { app_id: appId, limit, offset },
    }),

  create: (data: CreateFunctionRequest) => {
    console.log('Making API call to create function with data:', data);
    return api.post<FunctionDefinition>('/functions', data);
  },

  getById: (id: string) =>
    api.get<FunctionDefinition>(`/functions/${id}`),

  update: (id: string, data: UpdateFunctionRequest) =>
    api.put<FunctionDefinition>(`/functions/${id}`, data),

  delete: (id: string) =>
    api.delete(`/functions/${id}`),

  deploy: (id: string, force = false) =>
    api.post(`/functions/${id}/deploy`, { force }),

  // Function execution
  execute: (id: string, data: Omit<ExecuteFunctionRequest, 'function_id'>) =>
    api.post<ExecuteFunctionResponse>(`/functions/${id}/execute`, data),

  invoke: (id: string, data?: { input?: any }) =>
    api.post<ExecuteFunctionResponse>(`/functions/${id}/invoke`, data),
};

export const executionApi = {
  // Execution management
  list: (functionId?: string, limit = 50, offset = 0) =>
    api.get<{ executions: FunctionExecution[] }>('/executions', {
      params: { function_id: functionId, limit, offset },
    }),

  getById: (id: string) =>
    api.get<FunctionExecution>(`/executions/${id}`),

  cancel: (id: string) =>
    api.delete(`/executions/${id}`),

  getLogs: (id: string) => {
    console.debug(`[API] Fetching logs for execution ${id}`);
    return api.get<{ logs: string[] }>(`/executions/${id}/logs`)
      .then(response => {
        console.debug(`[API] Successfully fetched logs for execution ${id}:`, {
          logCount: response.data.logs?.length || 0,
          logs: response.data.logs
        });
        return response;
      })
      .catch(error => {
        console.error(`[API] Failed to fetch logs for execution ${id}:`, error);
        throw error;
      });
  },

  getRunning: () =>
    api.get<{ executions: FunctionExecution[]; count: number }>('/executions/running'),
};

export const healthApi = {
  health: () => api.get('/health'),
  ready: () => api.get('/ready'),
};

export const runtimeApi = {
  getRuntimes: () => api.get('/runtimes'),
};
