// Tarayıcıdan TKGM sorguları. TKGM, yurt dışı/veri merkezi IP'lerini (sunucumuz dahil) 403 ile engelleyebiliyor;
// API CORS'a açık olduğu için önce kullanıcının tarayıcısından doğrudan sorgulanır, olmazsa sunucu vekiline düşülür.
const CBS = 'https://cbsapi.tkgm.gov.tr/megsiswebapi.v3/api';
export type Opt = { id: number; text: string };
export type ParcelResult = { geometry: { type: 'Polygon'; coordinates: number[][][] }; il: string; ilce: string; mahalle: string; mevkii?: string; nitelik: string; pafta?: string; ada: string | number; parsel: string | number; alan: number;
  /** TKGM zemin durumu: "Ana Taşınmaz", "Kat Mülkiyeti", "Kat İrtifakı"… */ zemin?: string };

async function direct<T>(p: string, base = CBS): Promise<T> {
  // TKGM, yabancı Referer başlığı görünce 403 döndürüyor: referer gönderilmez.
  const r = await fetch(`${base}/${p}`, { signal: AbortSignal.timeout(12000), referrerPolicy: 'no-referrer', credentials: 'omit' });
  if (r.status === 404) throw Object.assign(new Error('Parsel bulunamadı'), { notFound: true });
  if (!r.ok) throw new Error(`TKGM ${r.status}`);
  return r.json();
}
async function viaServer<T>(url: string): Promise<T> {
  const r = await fetch(url); const j = await r.json().catch(() => ({}));
  if (!r.ok) throw Object.assign(new Error(j.error || 'TKGM yanıt vermedi'), { notFound: r.status === 404 });
  return j as T;
}
type FC = { features: { properties: { id: number; text: string } }[] };
const list = (j: FC) => j.features.map((f) => ({ id: f.properties.id, text: f.properties.text })).sort((a, b) => a.text.localeCompare(b.text, 'tr'));

// İl/ilçe/mahalle listeleri sunucudaki paketli kopyadan gelir; tarayıcı TKGM'ye gitmez.
export async function idariList(kind: 'il' | 'ilce' | 'mahalle', id?: string): Promise<Opt[]> {
  return viaServer<Opt[]>(kind === 'il' ? '/api/tkgm/il' : `/api/tkgm/${kind}/${id}`);
}

type F = { geometry: ParcelResult['geometry']; properties: Record<string, string | number> };
export async function parcelLookup(mahalleId: string, ada: string, parsel: string): Promise<ParcelResult> {
  // 1) Sunucu (TKGM_PROXY_URL / röle üzerinden); 2) olmazsa tarayıcıdan doğrudan TKGM (referer'sız).
  try { return await viaServer<ParcelResult>(`/api/tkgm/parsel?mahalleId=${mahalleId}&ada=${encodeURIComponent(ada)}&parsel=${encodeURIComponent(parsel)}`); }
  catch (e) {
    if ((e as { notFound?: boolean }).notFound) throw e;
    const q = `parsel/${Number(mahalleId)}/${Number(ada)}/${Number(parsel)}`;
    const f = await direct<F>(q).catch(() => direct<F>(q, 'https://cbsapi.tkgm.gov.tr/megsiswebapi.v3.1/api')).catch(() => { throw Object.assign(new Error('busy'), { busy: true }); });
    if (!f?.geometry) throw Object.assign(new Error('Parsel bulunamadı'), { notFound: true });
    const pr = f.properties;
    return { geometry: f.geometry, il: String(pr.ilAd), ilce: String(pr.ilceAd), mahalle: String(pr.mahalleAd), mevkii: String(pr.mevkii || ''),
      nitelik: String(pr.nitelik || '').trim(), pafta: String(pr.pafta || ''), ada: pr.adaNo, parsel: pr.parselNo, zemin: String(pr.zeminKmdurum || ''),
      alan: parseFloat(String(pr.alan || '0').replace(/\./g, '').replace(',', '.')) };
  }
}
