import {createHmac} from "node:crypto";
import {readFileSync} from "node:fs";

const baseUrl = "https://f-n8.ru";
const [keyId, secret] = readFileSync("/root/ghost-admin-api-key", "utf8").trim().split(":");
const encode = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
const now = Math.floor(Date.now() / 1000);
const unsigned = `${encode({alg: "HS256", typ: "JWT", kid: keyId})}.${encode({iat: now, exp: now + 300, aud: "/admin/"})}`;
const token = `${unsigned}.${createHmac("sha256", Buffer.from(secret, "hex")).update(unsigned).digest("base64url")}`;
const headers = {Authorization: `Ghost ${token}`, "Content-Type": "application/json"};

const oldText = "Мы собираем материалы производителей и профильных магазинов, проверяем их релевантность и приводим к единому удобному формату.";
const newText = "Ежедневно мы собираем новости снаряжения с сотен источников, отбираем лучшее и публикуем в одном месте!";

const response = await fetch(`${baseUrl}/ghost/api/admin/pages/slug/about/?formats=html`, {headers});
if (!response.ok) throw new Error(`Ghost page read failed: ${response.status} ${await response.text()}`);
const page = (await response.json()).pages[0];
const html = String(page.html || "");
if (!html.includes(oldText) && !String(page.custom_excerpt || "").includes(oldText)) {
  throw new Error("Expected about text was not found");
}
const update = {
  id: page.id,
  updated_at: page.updated_at,
  html: html.replaceAll(oldText, newText),
  custom_excerpt: String(page.custom_excerpt || "").replaceAll(oldText, newText),
};
const saved = await fetch(`${baseUrl}/ghost/api/admin/pages/${page.id}/?source=html`, {
  method: "PUT",
  headers,
  body: JSON.stringify({pages: [update]}),
});
if (!saved.ok) throw new Error(`Ghost page update failed: ${saved.status} ${await saved.text()}`);
const result = (await saved.json()).pages[0];
console.log(JSON.stringify({id: result.id, slug: result.slug, updated_at: result.updated_at}));
