import { useEffect, useState } from 'react';
import { fetchEventSource } from '@fortaine/fetch-event-source';

function getToken() {
  return window.localStorage.getItem('kiwi.token') || '';
}

const getHeaders = () => {
  const token = getToken();
  const appId = 'TzEU5jPk2tu80266';
  const appSecret = '0a006048a4480481b18fef1405120b83';
  const timestamp = Math.floor(Date.now() / 1000);

  return {
    Authorization: token,
    AppId: appId,
    AppSecret: appSecret,
    Timestamp: timestamp,
    'Content-Type': 'application/json',
  };
};

const defaultOnOpen = async (response) => {
  if (!response.ok) {
    throw response;
  }
  return response;
};

const defaultOnMessage = (setMessages) => (res) => {
  const message = JSON.parse(res.data);
  setMessages((prevMessages) => [...prevMessages, message]);
};

export function useFetchEventSource(url, options = {}) {
  const [isLoading, setLoading] = useState(false);
  const [messages, setMessages] = useState([]);
  const [error, setError] = useState(null);

  const fetch = () => {
    setLoading(true);
    const headers = getHeaders();

    const defaultOptions = {
      method: 'POST',
      headers,
      onopen: defaultOnOpen,
      onmessage: defaultOnMessage(setMessages),
      onerror: (err) => setError(err),
    };

    fetchEventSource(url, { ...defaultOptions, ...options }).finally(() => setLoading(false));
  };

  useEffect(() => {
    fetch();
  }, [url, options]);

  return { isLoading, error, messages };
}
