"use strict";

const test = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");

const root = path.resolve(__dirname, "..", "..");
const app = fs.readFileSync(path.join(root, "Web", "app.js"), "utf8");
const index = fs.readFileSync(path.join(root, "Web", "index.html"), "utf8");
const native = fs.readFileSync(path.join(root, "MainWindow.NamedNxtThemeRestore.cs"), "utf8");

function functionBody(name, nextName) {
  const start = app.indexOf(`function ${name}(`);
  const end = app.indexOf(`function ${nextName}(`, start + 1);
  assert.ok(start >= 0 && end > start, `${name} must precede ${nextName}`);
  return app.slice(start, end);
}

test("named NXT restore remains correlated through native, Web, and page preflight", () => {
  assert.match(index, /src="named-nxt-theme-restore-workflow\.js"/u);
  assert.match(native, /PostMessage\("named-nxt-theme-restore-results"/u);
  assert.match(app, /nxtThemeRestorePending/u);
  assert.match(app, /case "named-nxt-theme-restore-results"/u);
  const finalize = functionBody("finalizeNamedManualRestores", "handleNamedManualListResults");
  assert.match(finalize, /state\.namedPlaylist\.nxtThemeRestorePending/u);
  assert.match(finalize, /prepareNamedPagePreflight/u);
});

test("native-verified in-memory identity is not lost to an object clone before PREPARE", () => {
  const materialize = functionBody("materializeNamedRestoration", "namedPlaylistPrepareBlockers");
  assert.match(materialize,
    /namedNxtThemeRestoreWorkflow\.isMaterializedEntry\(row\.entry\)/u);
  assert.match(materialize,
    /trustedOperatorEntry[\s\S]*\? \(trustedOperatorEntry \? row\.entry : \{ \.\.\.row\.entry/u);
  const synchronize = functionBody("synchronizeThemeEntries", "clearOverseasTimeout");
  assert.match(synchronize,
    /namedNxtThemeRestoreWorkflow\.isMaterializedEntry\(refreshed\)[\s\S]*\? refreshed/u);
});

test("NXT restore preserves the old DB code for save while current code drives playout", () => {
  const fields = functionBody("namedLegacyFieldsForEntry", "isTrustedNamedPlaylistEntry");
  assert.match(fields, /legacySelectionForEntry\(entry\)/u);
  assert.match(fields, /matchesRaw\(entry, rawRow\)/u);
  assert.match(fields, /과거 code와 현재 송출 code/u);
});
