import { Hono } from 'hono';
import { supabase } from '../supabase.js';
import { requireAdmin } 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) => ({
    id: u.id,
    email: u.email,
    created_at: u.created_at,
    isAdmin: ADMINS.includes((u.email || '').toLowerCase()),
  }));
  return c.json(list);
});

users.post('/', async (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.admin.createUser({ email, password, email_confirm: true });
  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 } = await c.req.json();
  if (!password) return c.json({ error: 'Passwort nötig' }, 400);
  const { error } = await supabase.auth.admin.updateUserById(c.req.param('id'), { password });
  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;
