import { Hono } from 'hono';
import { supabase } from '../supabase.js';
import { requireAdmin, roleOf } from '../auth.js';
import { config } from '../config.js';
import * as local from '../auth-local.js';

// Autoren-/Nutzerverwaltung. Mit auth:'local' gegen die User-Datei (DB-los),
// sonst über die GoTrue-Admin-API (Service-Key). Nur Admins.
const ADMINS = (process.env.ADMIN_EMAILS || '')
  .split(',').map((s) => s.trim().toLowerCase()).filter(Boolean);
const isLocal = () => config.auth === 'local';

const users = new Hono();
users.use('*', requireAdmin);

users.get('/', async (c) => {
  if (isLocal()) {
    try { return c.json(await local.listUsers(ADMINS)); }
    catch (e) { return c.json({ error: String(e.message || e) }, 500); }
  }
  const { data, error } = await supabase.auth.admin.listUsers();
  if (error) return c.json({ error: error.message }, 500);
  const list = (data?.users || []).map((u) => {
    const role = roleOf(u);
    return {
      id: u.id,
      email: u.email,
      created_at: u.created_at,
      last_sign_in_at: u.last_sign_in_at || null,
      role,
      isAdmin: role === 'admin',
      // Admins aus der .env lassen sich nicht per UI herabstufen.
      fixedAdmin: ADMINS.includes((u.email || '').toLowerCase()),
    };
  });
  return c.json(list);
});

users.post('/', async (c) => {
  const { email, password, role } = await c.req.json();
  if (!email || !password) return c.json({ error: 'E-Mail und Passwort nötig' }, 400);
  if (role && !['user', 'editor', 'admin'].includes(role)) return c.json({ error: 'Unbekannte Rolle' }, 400);
  if (isLocal()) {
    try { return c.json({ ok: true, id: await local.createUser({ email, password, role }) }); }
    catch (e) { return c.json({ error: String(e.message || e) }, 400); }
  }
  const payload = { email, password, email_confirm: true };
  if (role && role !== 'user') payload.app_metadata = { role };
  const { data, error } = await supabase.auth.admin.createUser(payload);
  if (error) return c.json({ error: error.message }, 400);
  return c.json({ ok: true, id: data.user.id });
});

users.put('/:id', async (c) => {
  const { password, role } = await c.req.json();
  if (role && !['user', 'editor', 'admin'].includes(role)) return c.json({ error: 'Unbekannte Rolle' }, 400);
  if (!password && !role) return c.json({ error: 'Nichts zu ändern' }, 400);
  if (isLocal()) {
    try { await local.updateUser(c.req.param('id'), { password, role }); return c.json({ ok: true }); }
    catch (e) { return c.json({ error: String(e.message || e) }, 400); }
  }
  const patch = {};
  if (password) patch.password = password;
  if (role) patch.app_metadata = { role };
  const { error } = await supabase.auth.admin.updateUserById(c.req.param('id'), patch);
  if (error) return c.json({ error: error.message }, 400);
  return c.json({ ok: true });
});

users.delete('/:id', async (c) => {
  if (isLocal()) {
    try { await local.deleteUser(c.req.param('id')); return c.json({ ok: true }); }
    catch (e) { return c.json({ error: String(e.message || e) }, 400); }
  }
  const { error } = await supabase.auth.admin.deleteUser(c.req.param('id'));
  if (error) return c.json({ error: error.message }, 400);
  return c.json({ ok: true });
});

export default users;
