import { getApiFieldErrors } from "@/lib/api/errors";

/**
 * BE-101 — location-checked self check-in.
 *
 * The organizer decides per opportunity whether a QR scan must also prove the
 * volunteer is on site. When it must, the scan carries the device's position
 * and the server refuses it beyond the allowed radius (500 m by default) of the
 * opportunity's map pin. The distance check is the server's alone; the browser
 * only collects the position.
 *
 * **Live since 2026-10-03.** It was off because the write endpoints rejected
 * `requires_attendance_location` as an unknown key (422). The backend shipped
 * it: `['sometimes','boolean']` in `VolunteerOpportunityController`'s rules,
 * the flag is returned on the opportunity card and detail, and the self-scan
 * accepts `latitude`/`longitude`/`accuracy` — confirmed against the deployed
 * API, where the field is present on `GET /list-volunteer-opportunities/`.
 *
 * What switching this on turns on, so it can be checked in a browser:
 *   - the organizer's "require an on-site scan" choice is saved rather than
 *     ignored, and the form then requires a map pin;
 *   - a volunteer scanning a flagged opportunity is asked for location
 *     permission, and the scan carries the fix;
 *   - a refusal beyond the radius arrives as the server's `location` field
 *     error, which the scan screens already show.
 *
 * Needs HTTPS (or localhost) for `navigator.geolocation` to resolve at all,
 * and a denied permission must read as a refusal rather than a silent failure.
 */
export const ATTENDANCE_LOCATION_LIVE = true;

/** Shown to people only; the server holds the real (admin-editable) radius. */
export const ATTENDANCE_LOCATION_RADIUS_M = 500;

export interface ScanPosition {
  latitude: number;
  longitude: number;
  /** Metres, as the device reports it. */
  accuracy: number;
}

export function requiresAttendanceLocation(
  opportunity: { requires_attendance_location?: boolean | number | null } | null | undefined
): boolean {
  if (!ATTENDANCE_LOCATION_LIVE) return false;
  const flag = opportunity?.requires_attendance_location;
  return flag === true || flag === 1;
}

/** An i18n key, so each caller can toast it in the current language. */
export class ScanPositionError extends Error {
  /*
   * Written out rather than as a `constructor(public readonly …)` parameter
   * property: that form is TypeScript-only syntax that a type *stripper*
   * cannot handle, and `npm test` runs the source through Node's. The emitted
   * JavaScript is the same assignment either way.
   */
  readonly messageKey: string;

  constructor(messageKey: string) {
    super(messageKey);
    this.messageKey = messageKey;
  }
}

/**
 * One fresh fix. `maximumAge: 0` because a cached position from home is exactly
 * what the check exists to refuse.
 */
export function getScanPosition(): Promise<ScanPosition> {
  return new Promise((resolve, reject) => {
    if (typeof navigator === "undefined" || !navigator.geolocation) {
      reject(new ScanPositionError("COMMON.ATTENDANCE_LOCATION_UNSUPPORTED"));
      return;
    }
    navigator.geolocation.getCurrentPosition(
      (position) =>
        resolve({
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
          accuracy: Math.round(position.coords.accuracy),
        }),
      (error) =>
        reject(
          new ScanPositionError(
            error.code === error.PERMISSION_DENIED
              ? "COMMON.ATTENDANCE_LOCATION_DENIED"
              : error.code === error.TIMEOUT
                ? "COMMON.ATTENDANCE_LOCATION_TIMEOUT"
                : "COMMON.ATTENDANCE_LOCATION_UNAVAILABLE"
          )
        ),
      { enableHighAccuracy: true, timeout: 15_000, maximumAge: 0 }
    );
  });
}

let lastFix: { position: ScanPosition; at: number } | null = null;

/**
 * The fix taken when the camera opened is reused for the scan itself, unless
 * it is over a minute old — the camera may have sat open meanwhile.
 */
export async function getRecentScanPosition(): Promise<ScanPosition> {
  if (lastFix && Date.now() - lastFix.at < 60_000) return lastFix.position;
  const position = await getScanPosition();
  lastFix = { position, at: Date.now() };
  return position;
}

/**
 * The server says this opportunity needs a position and the scan had none —
 * the navbar scanner can't know in advance when the list payload lacks the
 * flag, so it asks and retries once.
 */
export function isLocationMissingError(error: unknown): boolean {
  return "latitude" in getApiFieldErrors(error);
}

/** Missing position, or too far from the pin: either way, a volunteering code. */
export function isLocationRejectedError(error: unknown): boolean {
  const fields = getApiFieldErrors(error);
  return "latitude" in fields || "location" in fields;
}
