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 cleanPkgName(v) {
  const s = String(v || "").trim();
  if (!s) return null;
  if (s.length > 64) return null;
  return s;
}

export function GET({ url }) {
  const pkg =
    cleanPkgName(url.searchParams.get("package")) ||
    cleanPkgName(url.searchParams.get("pckg_name"));

  if (!pkg) {
    return new Response(
      JSON.stringify({ ok: false, error: "MISSING_PACKAGE_NAME" }),
      {
        status: 400,
        headers: { "Content-Type": "application/json; charset=utf-8" },
      }
    );
  }

  const db = getDb();

  try {
    const rows = db
      .prepare(
        `
        SELECT
          nazwa     AS name,
          opis      AS description,
          image     AS logo_url
        FROM jambox_channels
        WHERE pckg_name = ?
        ORDER BY nazwa COLLATE NOCASE ASC;
        `.trim()
      )
      .all(pkg);

    return new Response(JSON.stringify({ ok: true, data: rows }), {
      status: 200,
      headers: { "Content-Type": "application/json; charset=utf-8" },
    });
  } catch (err) {
    console.error("Błąd w /api/jambox/jambox-channels-package:", 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 {}
  }
}
