import { prisma } from '@/lib/db';
import { tkgmFetch, tkgmVia, TKGM_BASES } from '@/lib/tkgm';
export const dynamic = 'force-dynamic';
const TKGM = process.env.TKGM_API_BASE || 'https://cbsapi.tkgm.gov.tr/megsiswebapi.v3/api';
/** ?deep=1 → dış bağımlılıkları da yoklar (TKGM). Gizli bilgi döndürmez. */
async function probe(url: string) {
  const t = Date.now();
  try { const r = await fetch(url, { signal: AbortSignal.timeout(10000), cache: 'no-store' }); return { status: r.status, ms: Date.now() - t }; }
  catch (e) { const c = (e as { cause?: { code?: string; message?: string } }).cause; return { error: c?.code || c?.message || (e as Error).message, ms: Date.now() - t }; }
}
async function probeTkgm() {
  const out: Record<string, unknown> = { via: tkgmVia() };
  for (const base of TKGM_BASES) {
    const t = Date.now();
    try {
      const r = await tkgmFetch('parsel/137536/101/5', 10000, base);
      const body = r.ok ? '' : (await r.text()).replace(/\s+/g, ' ').slice(0, 80);
      out[base.replace(/^https:\/\//, '')] = { status: r.status, ms: Date.now() - t, ...(body ? { body } : {}) };
    } catch (e) { out[base] = { error: (e as { cause?: { code?: string } }).cause?.code || (e as Error).message }; }
  }
  return out;
}
// Geçici tanı: yol kaynakları (Overpass /status sorgu kotası harcamaz; OpenFreeMap TileJSON + tek karo)
async function probeRoads() {
  const hosts = ['https://overpass-api.de/api', 'https://overpass.kumi.systems/api', 'https://overpass.private.coffee/api', 'https://maps.mail.ru/osm/tools/overpass/api'];
  const out: Record<string, unknown> = {};
  await Promise.all(hosts.map(async (h) => { out[new URL(h).host] = await probe(`${h}/status`); }));
  out.openfreemap = await probe('https://tiles.openfreemap.org/planet');
  return out;
}
export async function GET(req: Request) {
  const deep = new URL(req.url).searchParams.get('deep') === '1';
  try {
    await prisma.$queryRaw`SELECT 1`;
    return Response.json({ ok: true, db: true, ...(deep ? { ...(new URL(req.url).searchParams.get('roads') === '1' ? { roads: await probeRoads() } : {}),
      ...(new URL(req.url).searchParams.get('tkgm') === '1' ? { tkgm: await probeTkgm() } : {}), esri: await probe('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/10/400/600') } : {}), at: new Date().toISOString() });
  } catch { return Response.json({ ok: false, db: false }, { status: 503 }); }
}
