#!/usr/bin/env node
"use strict";

const assert = require("node:assert");

const BASE_URL = (process.env.MNOTE_UI_BASE_URL || "http://127.0.0.1:3000").replace(/\/$/, "");

async function main() {
  const response = await fetch(`${BASE_URL}/search?workspaceId=ws_demo&q=Rust`);
  const html = await response.text();
  assert.equal(response.status, 200, `/search 请求失败: ${response.status} ${html.slice(0, 200)}`);
  assert.equal(response.headers.get("x-mnote-web-shell"), "search");
  assert.match(html, /mnote\.search_shell\.v1/);
  assert.match(html, /search\.documents\.query/);
  assert.match(html, /data-search-results-owner="rust-kernel"/);
  assert.match(html, /search-result/);
  assert.doesNotMatch(html, /react_search_palette/);

  const api = await fetch(`${BASE_URL}/api/search/documents`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({
      workspaceId: "ws_demo",
      query: "Rust",
      filters: {
        titleOnly: false,
        exact: false,
        includeOcr: false,
        onlyCurrentPage: false,
        timeRange: "any",
        timeField: "updated",
      },
    }),
  });
  const payload = await api.json();
  assert.equal(api.status, 200, `/api/search/documents 请求失败: ${api.status}`);
  assert.equal(payload.projectionOwner, "rust-kernel");
  assert.equal(payload.meta.queryName, "search.documents.query");

  console.log(JSON.stringify({ ok: true, projectionOwner: payload.projectionOwner }, null, 2));
}

main().catch((error) => {
  console.error(error instanceof Error ? error.stack || error.message : String(error));
  process.exit(1);
});
