import { Hono } from 'hono';
import { supabase } from '../supabase.js';
import { requireAdmin, roleOf } from '../auth.js';

// Autoren-/Nutzerverwaltung über die GoTrue-Admin-API (Service-Key). Nur Admins.
const ADMINS = (process.env.ADMIN_EMAILS || '')
  .split(',').map((s) => s.trim().toLowerCase()).filter(Boolean);

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

users.get('/', async (c) => {
  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);
  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();
  const patch = {};
  if (password) patch.password = password;
  if (role) {
    if (!['user', 'editor', 'admin'].includes(role)) return c.json({ error: 'Unbekannte Rolle' }, 400);
    patch.app_metadata = { role };
  }
  if (!Object.keys(patch).length) return c.json({ error: 'Nichts zu ändern' }, 400);
  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) => {
  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;
