import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { supabase } from '../supabase.js';

// Dialog: flache Wortmeldungen pro Thread (= Beitrags-Pfad), optionaler Bezug.
const SITE_DIR = process.env.SITE_DIR || '/site';

// Anzeigename + Avatar aus dem Profil (data/authors.json), Fallback = Mail-Teil.
async function profileFor(email) {
  try {
    const all = JSON.parse(await readFile(path.join(SITE_DIR, 'data', 'authors.json'), 'utf8'));
    return all[email] || null;
  } catch { return null; }
}

const COLS = 'id,thread,parent_id,author_name,author_avatar,body,created_at,deleted';

// ÖFFENTLICH: Wortmeldungen eines Threads lesen.
export async function listComments(c) {
  const thread = c.req.query('thread');
  if (!thread) return c.json({ error: 'thread fehlt' }, 400);
  const { data, error } = await supabase
    .from('comments').select(COLS).eq('thread', thread).order('created_at', { ascending: true });
  if (error) return c.json({ error: error.message }, 500);
  const out = (data || []).map((r) => (r.deleted ? { ...r, body: '[gelöscht]', author_avatar: null } : r));
  return c.json(out);
}

// EINGELOGGT: Wortmeldung schreiben.
export async function createComment(c) {
  const user = c.get('user');
  const email = c.get('email');
  const { thread, body, parent_id } = await c.req.json();
  if (!thread || !body || !body.trim()) return c.json({ error: 'thread und Text nötig' }, 400);

  const prof = await profileFor(email);
  const row = {
    thread,
    parent_id: parent_id || null,
    user_id: user.id,
    author_name: prof?.name || email.split('@')[0],
    author_avatar: prof?.avatar || null,
    body: body.trim(),
  };
  const { data, error } = await supabase.from('comments').insert(row).select(COLS).single();
  if (error) return c.json({ error: error.message }, 400);
  return c.json(data, 201);
}

// EINGELOGGT: eigene Wortmeldung (oder als Admin jede) löschen.
export async function deleteComment(c) {
  const user = c.get('user');
  const isAdmin = c.get('isAdmin');
  const id = c.req.param('id');
  const { data: row, error: e1 } = await supabase.from('comments').select('user_id').eq('id', id).single();
  if (e1 || !row) return c.json({ error: 'Nicht gefunden' }, 404);
  if (!isAdmin && row.user_id !== user.id) return c.json({ error: 'Kein Recht' }, 403);
  const { error } = await supabase.from('comments').update({ deleted: true }).eq('id', id);
  if (error) return c.json({ error: error.message }, 400);
  return c.json({ ok: true });
}

// ÖFFENTLICH: Login fürs Dialog-Widget — gibt das User-Token zurück.
export async function login(c) {
  const { email, password } = await c.req.json();
  if (!email || !password) return c.json({ error: 'E-Mail und Passwort nötig' }, 400);
  const { data, error } = await supabase.auth.signInWithPassword({ email, password });
  if (error) return c.json({ error: error.message }, 401);
  const prof = await profileFor((data.user.email || '').toLowerCase());
  return c.json({
    access_token: data.session.access_token,
    email: data.user.email,
    name: prof?.name || (data.user.email || '').split('@')[0],
  });
}
