// API Service for_codigo0-nuevo

const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:3000/api';

export interface ProtocolStep {
  id: string;
  order: number;
  instruction: string;
  verification?: string;
  notes?: string;
  critical?: boolean;
}

export interface TelephoneProtocol {
  id: string;
  title: string;
  shortTitle: string;
  category: string;
  ageGroup: string;
  description: string;
  initialAssessment: string[];
  steps: ProtocolStep[];
  importantNotes?: string[];
  source?: string;
}

export interface ApiResponse<T> {
  message?: string;
  data: T;
  items?: T[];
  total?: number;
  page?: number;
  pageSize?: number;
}

// Helper function to handle API requests
async function fetchApi<T>(endpoint: string, options?: RequestInit): Promise<T> {
  const url = `${API_URL}${endpoint}`;
  const response = await fetch(url, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      ...options?.headers,
    },
  });

  if (!response.ok) {
    const errorData = await response.json().catch(() => ({}));
    throw new Error(errorData.message || `HTTP error! status: ${response.status}`);
  }

  return response.json();
}

// Protocol API functions
export const protocolApi = {
  // Get all protocols
  getAll: async (): Promise<ApiResponse<TelephoneProtocol[]>> => {
    return fetchApi<ApiResponse<TelephoneProtocol[]>>('/content');
  },

  // Get protocol by ID
  getById: async (id: string): Promise<ApiResponse<TelephoneProtocol>> => {
    return fetchApi<ApiResponse<TelephoneProtocol>>(`/content/${id}`);
  },

  // Search protocols
  search: async (query: string): Promise<ApiResponse<TelephoneProtocol[]>> => {
    return fetchApi<ApiResponse<TelephoneProtocol[]>>(`/content/search?query=${encodeURIComponent(query)}`);
  },
};

export default protocolApi;
