import { supabase, supabaseAuth } from '../../supabase.js';
import { roleOf } from '../../auth.js';
import { profileFor, threadLocked } from './dialog-store.js';
import { serverError } from '../../util.js';

// Dialog: flache Wortmeldungen pro Thread (= Thread-Key), optionaler Bezug.

const COLS = 'id,thread,parent_id,author_name,author_avatar,author_role,body,created_at,deleted';
const MAX_BODY = 10_000;     // Zeichen je Wortmeldung
const MAX_THREAD = 512;      // Thread-Key-Länge

// Ö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 serverError(c, 'listComments', error);
  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);
  if (typeof thread !== 'string' || thread.length > MAX_THREAD) return c.json({ error: 'Ungültiger Thread' }, 400);
  if (typeof body !== 'string' || body.length > MAX_BODY) return c.json({ error: `Text zu lang (max. ${MAX_BODY} Zeichen)` }, 400);
  if (await threadLocked(thread)) return c.json({ error: 'Thread ist gesperrt' }, 403);

  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,
    author_role: prof?.title || null,   // „Position bei OPENBUREAU" (aus data/authors.json)
    body: body.trim(),
  };
  const { data, error } = await supabase.from('comments').insert(row).select(COLS).single();
  if (error) return serverError(c, 'createComment', error, 400);
  return c.json(data, 201);
}

// EINGELOGGT: eigene Wortmeldung löschen; Moderation (Admin/Redakteur) jede.
export async function deleteComment(c) {
  const user = c.get('user');
  const canModerate = c.get('canModerate');
  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 (!canModerate && 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 serverError(c, 'deleteComment', error, 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 supabaseAuth.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],
    role: roleOf(data.user),
  });
}
