import { Hono } from 'hono';
import { supabase } from '../../supabase.js';
import { requireAdmin, requireModerator } from '../../auth.js';
import { serverError } from '../../util.js';
import {
  forumsWithCounts, forumWithThreads, recentComments, createThread, recentForModeration, threadMeta,
} from './dialog-store.js';

// Fehlt die Tabelle (Migration noch nicht eingespielt), nicht mit einem rohen
// SQL-Fehler antworten — leer zurückgeben und server-seitig laut loggen.
function softFail(c, e, fallback) {
  console.error('[dialog]', e?.message || e);
  return c.json(fallback);
}

// ── Öffentliche Lese-Handler ─────────────────────────────────────────────
export async function listForums(c) {
  try { return c.json(await forumsWithCounts()); }
  catch (e) { return softFail(c, e, []); }
}
export async function showForum(c) {
  try {
    const data = await forumWithThreads(c.req.param('slug'));
    if (!data) return c.json({ error: 'Forum nicht gefunden' }, 404);
    return c.json(data);
  } catch (e) { return softFail(c, e, { forum: null, threads: [] }); }
}
export async function recent(c) {
  try { return c.json(await recentComments(Number(c.req.query('limit')) || 20)); }
  catch (e) { return softFail(c, e, []); }
}
export async function threadInfo(c) {
  const key = c.req.query('key');
  if (!key) return c.json({ error: 'key fehlt' }, 400);
  const meta = await threadMeta(key);
  if (!meta) return c.json({ error: 'Thread nicht gefunden' }, 404);
  return c.json(meta);
}

// ── Eingeloggt: neuen Thread starten ─────────────────────────────────────
export async function newThread(c) {
  const user = c.get('user');
  const email = c.get('email');
  const { forum_id, forum_slug, title, body } = await c.req.json();
  const res = await createThread({ forumId: forum_id, forumSlug: forum_slug, title, body, user, email });
  if (res.error) return c.json({ error: res.error }, 400);
  return c.json(res.thread, 201);
}

// ── Moderation (Admin + Redakteur) ───────────────────────────────────────
export const mod = new Hono();
mod.use('*', requireModerator);
// Feed: letzte Wortmeldungen + alle Threads (zum Moderieren/Sperren).
mod.get('/overview', async (c) => c.json(await recentForModeration()));
// Thread sperren/entsperren.
mod.post('/thread-lock', async (c) => {
  const { key, locked } = await c.req.json();
  if (!key) return c.json({ error: 'key nötig' }, 400);
  const { error } = await supabase.from('threads').update({ locked: !!locked }).eq('key', key);
  if (error) return serverError(c, 'dialog', error, 400);
  return c.json({ ok: true });
});
// Thread ausblenden (löschen).
mod.post('/thread-delete', async (c) => {
  const { key } = await c.req.json();
  if (!key) return c.json({ error: 'key nötig' }, 400);
  const { error } = await supabase.from('threads').update({ deleted: true }).eq('key', key);
  if (error) return serverError(c, 'dialog', error, 400);
  return c.json({ ok: true });
});

// ── Foren-Verwaltung (nur Admin) ─────────────────────────────────────────
export const adminForums = new Hono();
adminForums.use('*', requireAdmin);
adminForums.get('/', async (c) => {
  const { data, error } = await supabase.from('forums').select('*').order('sort');
  if (error) return serverError(c, 'dialog', error, 500);
  return c.json(data || []);
});
adminForums.post('/', async (c) => {
  const { slug, name, description, color, sort } = await c.req.json();
  if (!slug || !name) return c.json({ error: 'slug und name nötig' }, 400);
  const row = { slug: String(slug).trim(), name: String(name).trim(),
    description: description || '', color: color || null, sort: Number(sort) || 0 };
  const { data, error } = await supabase.from('forums').insert(row).select('*').single();
  if (error) return serverError(c, 'dialog', error, 400);
  return c.json(data, 201);
});
adminForums.put('/:id', async (c) => {
  const patch = await c.req.json();
  const allowed = {};
  for (const k of ['name', 'description', 'color', 'sort', 'slug']) if (k in patch) allowed[k] = patch[k];
  const { data, error } = await supabase.from('forums').update(allowed).eq('id', c.req.param('id')).select('*').single();
  if (error) return serverError(c, 'dialog', error, 400);
  return c.json(data);
});
adminForums.delete('/:id', async (c) => {
  const id = c.req.param('id');
  const { data: f } = await supabase.from('forums').select('kind').eq('id', id).single();
  if (f?.kind === 'library') return c.json({ error: 'Beiträge-Kategorie kann nicht gelöscht werden' }, 400);
  const { error } = await supabase.from('forums').delete().eq('id', id);
  if (error) return serverError(c, 'dialog', error, 400);
  return c.json({ ok: true });
});
