import { erp } from '../config';

let cachedToken: string | null = null;

async function login(): Promise<string> {
  const res = await fetch(`${erp.apiUrl}/auth/login`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ username: erp.username, password: erp.password }),
  });

  if (!res.ok) {
    throw new Error(`ERP login failed: ${res.status} ${res.statusText}`);
  }

  const data = await res.json();
  cachedToken = data.token;
  return cachedToken;
}

async function getToken(): Promise<string> {
  if (cachedToken) return cachedToken;
  return login();
}

export async function fetchSales(startDate: string, endDate: string): Promise<unknown[]> {
  const token = await getToken();

  const url = new URL(`${erp.apiUrl}/api/getbydate`);
  url.searchParams.set('startDate', startDate);
  url.searchParams.set('endDate', endDate);
  url.searchParams.set('code', erp.apiCode);

  const res = await fetch(url.toString(), {
    headers: { Authorization: `Bearer ${token}` },
  });

  // Token expired — re-login and retry once
  if (res.status === 401) {
    cachedToken = null;
    const freshToken = await login();

    const retry = await fetch(url.toString(), {
      headers: { Authorization: `Bearer ${freshToken}` },
    });

    if (!retry.ok) {
      throw new Error(`ERP fetch failed after re-login: ${retry.status}`);
    }
    return retry.json();
  }

  if (!res.ok) {
    throw new Error(`ERP fetch failed: ${res.status} ${res.statusText}`);
  }

  return res.json();
}

export function isConfigured(): boolean {
  return !!(erp.apiUrl && erp.apiCode && erp.username && erp.password);
}
