/**
 * geotracker-lupmis.js — LUPMIS2 integration layer for the reusable GeoTracker.
 *
 * This is the ONLY place that couples the generic src/geotracker/ engine to
 * LUPMIS specifics (SQLocal storage, the PHP sync endpoint, district id,
 * online checks). To reuse GeoTracker in another app, copy src/geotracker/ and
 * write a file like this one with that app's storage + sync adapters.
 *
 * @module geotracker-lupmis
 */

import { GeoTracker } from './geotracker/GeoTracker.js';
import {
  createGpsTrail,
  addGpsTrailPoint,
  finishGpsTrail,
  getUnsyncedGpsTrails,
  getGpsTrailPoints,
  markGpsTrailSynced,
} from './database.js';
import { pushGpsTrail } from './remotedb.js';
import { isOnline } from './pwa.js';
import { getSession } from './remotedb.js';

/**
 * Storage adapter — maps the GeoTracker contract onto the SQLocal helpers in
 * database.js. The district id is stamped onto each trail at creation time.
 */
const sqlocalStorage = {
  async createTrail(meta) {
    const districtId = meta.districtId
      ?? getSession()?.district_id
      ?? null;
    return createGpsTrail({ ...meta, districtId: districtId != null ? String(districtId) : null });
  },
  addPoint:        (trailId, point)   => addGpsTrailPoint(trailId, point),
  finishTrail:     (trailId, summary) => finishGpsTrail(trailId, summary),
  getUnsyncedTrails: ()               => getUnsyncedGpsTrails(),
  getTrailPoints:  (trailId)          => getGpsTrailPoints(trailId),
  markTrailSynced: (trailId, remote)  => markGpsTrailSynced(trailId, remote),
};

/**
 * Sync adapter — store-and-forward upload via the PHP endpoint. `isOnline()`
 * lets the tracker skip pushes while offline (it retries later).
 */
const remoteSync = {
  pushTrail: (trail, points) => pushGpsTrail(trail, points),
  isOnline:  () => isOnline(),
};

/**
 * The configured, app-wide tracker instance. Tunables chosen for field
 * walking/driving: a point every ~5 m, throttled to ≥1 s, with a 20 s
 * heartbeat so stationary pauses still leave a breadcrumb, dropping fixes
 * worse than 50 m accuracy.
 */
export const geoTracker = new GeoTracker({
  storage: sqlocalStorage,
  sync: remoteSync,
  minDistanceM: 5,
  minIntervalMs: 1000,
  heartbeatMs: 20000,
  maxAccuracyM: 50,
  enableHighAccuracy: true,
});

export default geoTracker;
