import { Hono } from 'hono';
import { urlFor, safeRel } from '../files.js';
import { buildSite, gitCommit } from '../hugo.js';
import { manager } from '../plugins.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 });
    // Plugin-Publish-Hooks anstoßen (dialog spiegelt neue Library-Beiträge sofort
    // als Threads). Fehler dürfen das Publish nicht kippen — Hooks fangen selbst ab.
    await manager.runPublish({}, { path: safe });
    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;
