/**
 * useCityPreference — composes cityStore with auth-aware PUT to persist city to DB.
 *
 * Design decisions:
 * - No useMe/useSession hook exists. DB→client sync of preferredCityCode is deferred —
 *   SSR cookie hint (md_city_hint set server-side from JWT claim) is the source of truth
 *   for initial city resolution. This keeps Wave 2 self-contained.
 * - Auth detection: document.documentElement.dataset.auth === 'user' (same pattern as
 *   usePersonalization, the existing mhv hook).
 * - Cookie md_city_hint mirrors cityCode for SSR personalization on next request.
 */

import { useCallback } from 'react';
import { useCityStore } from '@/lib/state/cityStore.js';
import { captureCaught } from '@/lib/observability';

const COOKIE = 'md_city_hint';
const COOKIE_DAYS = 365;

function setCookie(value: string | null): void {
  if (typeof document === 'undefined') return;
  if (value === null) {
    document.cookie = `${COOKIE}=; Max-Age=0; Path=/; SameSite=Lax`;
    return;
  }
  const exp = new Date(Date.now() + COOKIE_DAYS * 864e5).toUTCString();
  document.cookie = `${COOKIE}=${encodeURIComponent(value)}; Expires=${exp}; Path=/; SameSite=Lax`;
}

function isAuthenticated(): boolean {
  if (typeof document === 'undefined') return false;
  return document.documentElement.dataset.auth === 'user';
}

export function useCityPreference() {
  const { cityCode, setCity, radius, setRadius } = useCityStore();

  /**
   * Choose a city by code.
   * - Updates zustand store (clears radius per setCity semantics)
   * - Mirrors to md_city_hint cookie for SSR
   * - PUT to /api/me/preferences/city when authenticated (fire-and-forget)
   */
  const choose = useCallback(
    (code: string | null) => {
      setCity(code);
      setCookie(code);

      if (isAuthenticated() && code !== null) {
        fetch('/api/me/preferences/city', {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ cityCode: code }),
          credentials: 'include',
        }).catch((err) => {
          captureCaught(err, { scope: 'lib.hooks.useCityPreference.choose', severity: 'info' });
        });
      }
    },
    [setCity],
  );

  return { cityCode, radius, choose, setRadius };
}
