import replaceAndRemoveTrailingSlash from '../utils/ReplaceAndRemoveTrailingSlash';

const NOTIFICATION_BASE_URL = 'https://api1.parinaam.in/api/notify/';

export function createApiFunction(apiUrl: string) {
  console.log(apiUrl, "urlllll");

  return {
    post: (data: FormData | Record<string, any>, id: string = '') => {
      const url = `${apiUrl}/${id}`;
      return fetchData(url, 'POST', data);
    },
    patch: (id: string | number, data: FormData | Record<string, any>) => {
      const url = `${apiUrl}/${id}`;
      return fetchData(url, 'PATCH', data);
    },
    put: (id: string | number, data: FormData | Record<string, any>) => {
      const url = `${apiUrl}/${id}`;
      return fetchData(url, 'PUT', data);
    },
  };
}

async function fetchData(
  url: string,
  method: string,
  data: FormData | Record<string, any>,
) {
  const headers: Record<string, any> = {
    'Access-Control-Allow-Origin': '*',
  };

  if (!(data instanceof FormData)) {
    headers['Content-Type'] = 'application/json';
  }

  const options = {
    method: method,
    headers,
    body: data ? createRequestBody(data) : undefined,
  };

  try {
    const fullUrl = NOTIFICATION_BASE_URL + replaceAndRemoveTrailingSlash(url);
    console.log(`Fetching URL: ${fullUrl}`);
    console.log('Request options:', options);

    const response = await fetch(fullUrl, options);

    const textResponse = await response.text(); // Get the raw response text
    console.log('Raw response:', textResponse);

    if (!response.ok) {
      console.error('HTTP error:', response.status, response.statusText);
      throw new Error(`HTTP error: ${response.status} ${response.statusText}`);
    }

    let jsonResponse;
    try {
      jsonResponse = JSON.parse(textResponse); // Attempt to parse JSON
    } catch (jsonError) {
      console.error('Error parsing JSON:', jsonError);
      throw new Error(`Error parsing JSON: ${jsonError}`);
    }

    return jsonResponse;
  } catch (error) {
    console.error('Fetch error:', error);
    throw error;
  }
}

function createRequestBody(data: FormData | Record<string, any>) {
  return data instanceof FormData ? data : JSON.stringify(data);
}
