import { Hono } from 'hono';
import { listEntries, readEntry, writeEntry, entryExists, hasAccess, normAuthors } from '../files.js';

// Dateibasiert + Rechte: Admin sieht/bearbeitet alles, Autor:innen nur Einträge,
// in denen ihre Mail unter `authors` steht.
const content = new Hono();

content.get('/', async (c) => {
  const email = c.get('email'); const isAdmin = c.get('isAdmin');
  try {
    let items = await listEntries();
    if (!isAdmin) items = items.filter((e) => hasAccess(e.authors, email));
    return c.json(items);
  } catch (e) { return c.json({ error: String(e.message || e) }, 500); }
});

content.get('/entry', async (c) => {
  const email = c.get('email'); const isAdmin = c.get('isAdmin');
  try {
    const entry = await readEntry(c.req.query('path'));
    if (!isAdmin && !hasAccess(entry.frontmatter.authors, email)) {
      return c.json({ error: 'Kein Zugriff auf diesen Eintrag' }, 403);
    }
    return c.json(entry);
  } catch (e) { return c.json({ error: String(e.message || e) }, 400); }
});

content.put('/entry', async (c) => {
  const email = c.get('email'); const isAdmin = c.get('isAdmin');
  const { path: rel, frontmatter, body } = await c.req.json();
  try {
    const exists = await entryExists(rel);
    if (exists && !isAdmin) {
      const cur = await readEntry(rel);
      if (!hasAccess(cur.frontmatter.authors, email)) {
        return c.json({ error: 'Kein Zugriff auf diesen Eintrag' }, 403);
      }
    }
    // authors zusammenführen; Ersteller wird beim Anlegen automatisch Autor.
    const authors = normAuthors(frontmatter.authors);
    if (!exists && email && !authors.some((a) => a.toLowerCase() === email)) {
      authors.unshift(email);
    }
    const fm = { ...frontmatter, authors };
    const saved = await writeEntry(rel, fm, body);
    return c.json({ ok: true, path: saved, created: !exists });
  } catch (e) { return c.json({ error: String(e.message || e) }, 400); }
});

export default content;
