import { WORKER_SELECTABLE_SERVICE_AREAS } from '@ehandyhire/shared';
import type { ServiceAreaKey } from '@/lib/geocode';
import {
  isEntireRegion,
  isShowAllBrowseArea,
  parseServiceArea,
  readStoredRegionSlug,
} from '@/lib/region';
import { detectRegionSlugFromBrowser } from '@/lib/regionGeolocation';

const WORKER_CITY_SET = new Set<string>(WORKER_SELECTABLE_SERVICE_AREAS);
const FALLBACK_WORKER_AREA: ServiceAreaKey = 'DAVAO_CITY';

/** Map a browse-region slug to a worker-selectable city key, if applicable. */
export function workerAreaKeyFromSlug(slug: string): ServiceAreaKey | null {
  const area = parseServiceArea(slug);
  if (!area || isShowAllBrowseArea(area) || isEntireRegion(area)) return null;
  if (!WORKER_CITY_SET.has(area)) return null;
  return area as ServiceAreaKey;
}

/** Read a default worker city synchronously from the saved browse region. */
export function readDefaultWorkerServiceAreaSync(): ServiceAreaKey | null {
  const stored = readStoredRegionSlug();
  if (!stored) return null;
  return workerAreaKeyFromSlug(stored);
}

/** Detect the nearest worker city from browser location or saved browse region. */
export async function detectDefaultWorkerServiceArea(): Promise<ServiceAreaKey> {
  const fromStored = readDefaultWorkerServiceAreaSync();
  if (fromStored) return fromStored;

  const slug = await detectRegionSlugFromBrowser();
  if (slug) {
    const fromGeo = workerAreaKeyFromSlug(slug);
    if (fromGeo) return fromGeo;
  }

  return FALLBACK_WORKER_AREA;
}
