import { Hono } from 'hono';
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import path from 'node:path';

// Profile als Hugo-Data-Datei: data/authors.json (Map E-Mail → Profil).
// So kann das Theme die Autor:innen via site.Data.authors rendern.
const SITE_DIR = process.env.SITE_DIR || '/site';
const FILE = path.join(SITE_DIR, 'data', 'authors.json');

async function readAll() {
  try { return JSON.parse(await readFile(FILE, 'utf8')); } catch { return {}; }
}

const profile = new Hono();

profile.get('/', async (c) => {
  const email = c.get('user')?.email || 'default';
  const all = await readAll();
  return c.json({ email, name: '', bio: '', avatar: '', ...(all[email] || {}) });
});

profile.put('/', async (c) => {
  const email = c.get('user')?.email || 'default';
  const { name, bio, avatar } = await c.req.json();
  const all = await readAll();
  all[email] = { name: name || '', bio: bio || '', avatar: avatar || '' };
  await mkdir(path.dirname(FILE), { recursive: true });
  await writeFile(FILE, JSON.stringify(all, null, 2) + '\n', 'utf8');
  return c.json({ ok: true });
});

export default profile;
