/**
 * Cron: Refresh Address Cache — runs daily at midnight UTC.
 *
 * Fetches the cities list from data.gov.il and stores it in R2 so the
 * /api/address/cities endpoint can serve from cache instead of hitting the
 * flaky upstream. Streets are lazy-cached per city code on first request.
 */

import { captureCaught } from '@/server/observability/capture.server';
import { putObject } from '../storage/r2.js';
import type { CronEnv } from './deal-expiry.js';

const CITIES_R2_KEY = 'cache/address/cities.json';

const DATA_GOV_CITIES_URL = new URL('https://data.gov.il/api/3/action/datastore_search');
DATA_GOV_CITIES_URL.searchParams.set('resource_id', '5c78e9fa-c2e2-4771-93ff-7f400a12f7ba');
DATA_GOV_CITIES_URL.searchParams.set('limit', '1500');
DATA_GOV_CITIES_URL.searchParams.set('fields', 'סמל_ישוב,שם_ישוב');

export async function runRefreshAddressCache(env: CronEnv): Promise<void> {
  if (!env.R2_BUCKET) {
    return;
  }

  try {
    const upstream = await fetch(DATA_GOV_CITIES_URL.toString(), {
      headers: {
        'User-Agent': 'Mozilla/5.0 (compatible; Multideal/1.0; +https://multi.deal)',
        Accept: 'application/json',
      },
      signal: AbortSignal.timeout(10_000),
    });

    if (!upstream.ok) {
      captureCaught(new Error(`Cities upstream error ${upstream.status}`), {
        scope: 'server.cron.refresh-address-cache',
        severity: 'warning',
      });
      return;
    }

    const body = await upstream.arrayBuffer();
    await putObject(env.R2_BUCKET, CITIES_R2_KEY, body, {
      contentType: 'application/json',
    });
  } catch (err) {
    captureCaught(err, { scope: 'server.cron.refresh-address-cache', severity: 'warning' });
  }
}
