import test from "node:test";
import assert from "node:assert/strict";

import { parseStoredSessionRecord } from "../shared/schema.js";

test("parseStoredSessionRecord migrates legacy session shape into current schema", () => {
  const migrated = parseStoredSessionRecord({
    messages: [
      { role: "user", text: "hello", meta: "ignored" },
      { role: "assistant", text: "world", details: { screenshotDataUrl: "data:image/png;base64,abc" } }
    ],
    currentContext: {
      page: { title: "Legacy Page", url: "https://example.com" },
      screenshotDataUrl: "data:image/png;base64,abc",
      screenshotMeta: { format: "png" }
    }
  });

  assert.deepEqual(migrated.chatSession.messages.map((item) => item.text), ["hello", "world"]);
  assert.deepEqual(migrated.chatSession.attachmentCache, {
    pageContextHash: "",
    screenshotHash: ""
  });
  assert.equal(migrated.pageSnapshot.page.title, "Legacy Page");
  assert.equal(migrated.pageSnapshot.screenshotDataUrl, undefined);
  assert.equal(migrated.pageSnapshot.screenshotMeta, undefined);
});

test("parseStoredSessionRecord accepts current schema unchanged", () => {
  const session = parseStoredSessionRecord({
    chatSession: {
      messages: [{ role: "assistant", text: "new session" }],
      attachmentCache: {
        pageContextHash: "page-hash",
        screenshotHash: "shot-hash"
      }
    },
    pageSnapshot: {
      page: { title: "Current Page" }
    }
  });

  assert.equal(session.chatSession.messages[0].text, "new session");
  assert.deepEqual(session.chatSession.attachmentCache, {
    pageContextHash: "page-hash",
    screenshotHash: "shot-hash"
  });
  assert.equal(session.pageSnapshot.page.title, "Current Page");
});
