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

// Self-service for the logged-in user (after requireAuth). Currently: change own
// password — local provider edits the user file; supabase verifies the current
// password then updates via the admin API.
const account = new Hono();

account.post('/password', async (c) => {
  let body = {};
  try { body = await c.req.json(); } catch { /* 400 below */ }
  const { current, next } = body;
  if (!next || String(next).length < 6) return c.json({ error: 'Neues Passwort zu kurz (min. 6 Zeichen).' }, 400);
  const email = (c.get('email') || '').toLowerCase();
  const userId = c.get('user')?.id;

  if (config.auth === 'local') {
    const u = (await local.loadUsers()).find((x) => (x.email || '').toLowerCase() === email);
    if (!u || !(await local.verifyPassword(current || '', u.password))) {
      return c.json({ error: 'Aktuelles Passwort ist falsch.' }, 403);
    }
    await local.updateUser(u.id, { password: next });
    return c.json({ ok: true });
  }

  // supabase: verify current via the dedicated auth client, then update via admin.
  if (!supabaseAuth || !supabase) return c.json({ error: 'Auth nicht verfügbar' }, 500);
  const { error: e1 } = await supabaseAuth.auth.signInWithPassword({ email, password: current || '' });
  await supabaseAuth.auth.signOut().catch(() => {}); // Session sofort wieder lösen
  if (e1) return c.json({ error: 'Aktuelles Passwort ist falsch.' }, 403);
  const { error: e2 } = await supabase.auth.admin.updateUserById(userId, { password: next });
  if (e2) return c.json({ error: e2.message }, 400);
  return c.json({ ok: true });
});

export default account;
