import { useState } from 'react';
import { storage, STORAGE_KEYS } from '../utils/localStorage';
import { parseUrlToParameters } from '../utils/urlParser';

export const useRequestHistory = (setters) => {
  // Load initial request history from localStorage
  const [requestHistory, setRequestHistory] = useState(() =>
    storage.get(STORAGE_KEYS.REQUEST_HISTORY, [])
  );

  const addToHistory = (url, response) => {
    let responsePreview = 'No response';

    try {
      if (response) {
        responsePreview = JSON.stringify(response).slice(0, 100) + '...';
      }
    } catch (error) {
      console.error('Error stringifying response for history:', error);
      responsePreview = 'Response cannot be displayed';
    }

    const newEntry = {
      id: Date.now(),
      url,
      timestamp: new Date().toISOString(),
      responsePreview
    };

    const updatedHistory = [newEntry, ...requestHistory.slice(0, 9)];
    setRequestHistory(updatedHistory);

    // Persist to localStorage
    storage.set(STORAGE_KEYS.REQUEST_HISTORY, updatedHistory);
  };

  const loadFromHistory = (historyItem) => {
    // Parse URL and set all the parameters
    try {
      parseUrlToParameters(historyItem.url, setters);
      return historyItem.url;
    } catch (error) {
      console.error('Error loading from history:', error);
      return '';
    }
  };

  return {
    requestHistory,
    addToHistory,
    loadFromHistory
  };
};
