import { refreshToken } from './auth';
import { extractApiError } from './apiError';

const API_URL = import.meta.env.VITE_EFC_API_URL;

export async function fetchDocuments(token, queryString = '') {
  let url = `${API_URL}/customs/pedimentos/`;
  if (queryString) url += `?${queryString}`;

  let res = await fetch(url, {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });

  if (res.status === 401) {
    const refresh = localStorage.getItem('refresh');
    if (refresh) {
      try {
        const data = await refreshToken(refresh);
        localStorage.setItem('access', data.access);
        res = await fetch(`${API_URL}/customs/pedimentos/`, {
          headers: {
            'Authorization': `Bearer ${data.access}`,
            'Content-Type': 'application/json',
          },
        });
      } catch {
        throw new Error('SESSION_EXPIRED');
      }
    } else {
      throw new Error('SESSION_EXPIRED');
    }
  }

  if (!res.ok) throw new Error(await extractApiError(res));
  return res.json();
}

export async function fetchDocumentById(token, id) {
  let res = await fetch(`${API_URL}/record/documents/?page=1&page_size=10&pedimento=${id}/`, {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });

  if (res.status === 401) {
    const refresh = localStorage.getItem('refresh');
    if (refresh) {
      try {
        const data = await refreshToken(refresh);
        localStorage.setItem('access', data.access);
        res = await fetch(`${API_URL}/record/documents/?page=1&page_size=10&pedimento=${id}/`, {
          headers: {
            'Authorization': `Bearer ${data.access}`,
            'Content-Type': 'application/json',
          },
        });
      } catch {
        throw new Error('SESSION_EXPIRED');
      }
    } else {
      throw new Error('SESSION_EXPIRED');
    }
  }

  if (!res.ok) throw new Error(await extractApiError(res));
  return res.json();
}
