import { catalogosApi, otsApi, vehiculosApi } from './api';
import { cacheCatalogList } from './catalogos-offline';
import { syncRemoteClientesCache } from './offline-clientes';
import { cacheRemoteOtList } from './offline-ots';
import { cacheRemoteVehiculos } from './offline-vehiculos';

const OFFLINE_BOOTSTRAP_KEY = 'offlineBootstrapAt';
const OFFLINE_BOOTSTRAP_INTERVAL = 15 * 60 * 1000;

export async function bootstrapOfflineData(force = false): Promise<boolean> {
  if (typeof window === 'undefined') return false;
  if (!navigator.onLine) return false;
  if (!localStorage.getItem('token')) return false;

  const lastRun = Number(localStorage.getItem(OFFLINE_BOOTSTRAP_KEY) || '0');
  if (!force && Date.now() - lastRun < OFFLINE_BOOTSTRAP_INTERVAL) {
    return false;
  }

  await Promise.allSettled([
    syncRemoteClientesCache(),
    (async () => {
      const response = await otsApi.list({ page: 1, limit: 1000 });
      const rows = response?.data || [];
      if (Array.isArray(rows) && rows.length > 0) {
        await cacheRemoteOtList(rows);
      }
    })(),
    (async () => {
      const vehiculos = await vehiculosApi.list();
      if (Array.isArray(vehiculos) && vehiculos.length > 0) {
        await cacheRemoteVehiculos(vehiculos);
      }
    })(),
    (async () => {
      const tiposVehiculo = await catalogosApi.tiposVehiculo();
      await cacheCatalogList('tipo_vehiculo', tiposVehiculo || []);
    })(),
    (async () => {
      const tiposDano = await catalogosApi.tiposDano();
      await cacheCatalogList('tipo_dano', tiposDano || []);
    })(),
    (async () => {
      const cosasTrae = await catalogosApi.cosasTrae();
      await cacheCatalogList('cosa_trae', cosasTrae || []);
    })(),
  ]);

  localStorage.setItem(OFFLINE_BOOTSTRAP_KEY, Date.now().toString());
  return true;
}

export function markOfflineBootstrapStale(): void {
  if (typeof window === 'undefined') return;
  localStorage.removeItem(OFFLINE_BOOTSTRAP_KEY);
}