import { Hono } from 'hono';
import { urlFor, safeRel } from '../files.js';
import { buildSite, gitCommit } from '../hugo.js';
import { syncLibrary } from '../dialog-store.js';

// Publizieren: public/ neu bauen (ohne Drafts) → live. Optional git-commit.
const publish = new Hono();

publish.post('/', async (c) => {
  const { path: rel } = await c.req.json();
  try {
    const safe = safeRel(rel);
    const build = await buildSite({ dest: 'public', drafts: false });
    // Neue/aktualisierte Library-Beiträge sofort als Dialog-Threads spiegeln.
    await syncLibrary({ force: true }).catch(() => {});
    const git = await gitCommit(`cms: publish ${safe}`).catch((e) => ({ error: String(e.message || e) }));
    return c.json({ ok: true, url: urlFor(safe), git, hugo: build.stdout });
  } catch (e) {
    return c.json({ error: String(e.message || e) }, 500);
  }
});

export default publish;
