import Database from "better-sqlite3";

const DB_PATH = process.env.FUZ_DB_PATH || "./src/data/ServicesRange.db";

function getDb() {
  return new Database(DB_PATH, { readonly: true });
}

function clamp(n, min, max) {
  return Math.max(min, Math.min(max, n));
}

function uniq(arr) {
  return Array.from(new Set(arr));
}

function slugifyPkg(name) {
  return String(name || "")
    .toLowerCase()
    .replace(/\s+/g, " ")
    .trim()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/(^-|-$)/g, "");
}

function uniqByKey(list, keyFn) {
  const seen = new Set();
  const out = [];
  for (const it of list || []) {
    const k = keyFn(it);
    if (!k || seen.has(k)) continue;
    seen.add(k);
    out.push(it);
  }
  return out;
}

export function GET({ url }) {
  const q = (url.searchParams.get("q") || "").trim();
  const limit = clamp(Number(url.searchParams.get("limit") || 50), 1, 200);

  if (q.length < 1) {
    return new Response(JSON.stringify({ ok: true, data: [] }), {
      status: 200,
      headers: { "Content-Type": "application/json; charset=utf-8" },
    });
  }

  const safe = q.replace(/[%_]/g, (m) => `\\${m}`);
  const like = `%${safe}%`;

  const db = getDb();

  try {
    const rows = db
      .prepare(
        `
        SELECT
          nazwa AS name,
          MAX(image) AS logo_url,
          MAX(opis)  AS description,

          -- ✅ pakiety główne (pckg_addons = 0)
          GROUP_CONCAT(
            CASE WHEN IFNULL(pckg_addons, 0) = 0 THEN pckg_name END,
            '||'
          ) AS packages_blob,

          -- ✅ pakiety tematyczne (pckg_addons = 1) + tid
          GROUP_CONCAT(
            CASE
              WHEN IFNULL(pckg_addons, 0) = 1 AND tid IS NOT NULL
              THEN CAST(tid AS TEXT) || '::' || pckg_name
            END,
            '||'
          ) AS thematic_blob

        FROM jambox_channels
        WHERE nazwa LIKE ? ESCAPE '\\'
        GROUP BY nazwa
        ORDER BY name COLLATE NOCASE ASC
        LIMIT ?;
        `.trim()
      )
      .all(like, limit);

    const data = rows.map((r) => {
      // ===== główne =====
      const pkgsRaw = String(r.packages_blob || "")
        .split("||")
        .map((x) => x.trim())
        .filter(Boolean);

      const packages = uniq(pkgsRaw)
        .map((p) => ({ id: slugifyPkg(p), name: p }))
        .sort((a, b) => a.name.localeCompare(b.name, "pl"));

      // ===== tematyczne =====
      const thematicRaw = String(r.thematic_blob || "")
        .split("||")
        .map((x) => x.trim())
        .filter(Boolean);

      const thematic_packages = uniqByKey(
        thematicRaw
          .map((x) => {
            const [tid, ...rest] = x.split("::");
            const name = rest.join("::").trim();
            const t = String(tid || "").trim();
            return t && name ? { tid: t, name } : null;
          })
          .filter(Boolean),
        (p) => `${p.tid}::${p.name}`
      ).sort((a, b) => a.name.localeCompare(b.name, "pl"));

      return {
        name: r.name,
        logo_url: r.logo_url || "",
        description: r.description || "",
        packages,
        thematic_packages, // ✅ NOWE
      };
    });

    return new Response(JSON.stringify({ ok: true, data }), {
      status: 200,
      headers: { "Content-Type": "application/json; charset=utf-8" },
    });
  } catch (err) {
    console.error("Błąd w /api/jambox/jambox-channels-search:", err);
    return new Response(JSON.stringify({ ok: false, error: "DB_ERROR" }), {
      status: 500,
      headers: { "Content-Type": "application/json; charset=utf-8" },
    });
  } finally {
    try {
      db.close();
    } catch {}
  }
}
