/**
 * GET    /api/auth/idp-credentials → { username, password }   (decrypted)
 * POST   /api/auth/idp-credentials   body: { username, password }
 * DELETE /api/auth/idp-credentials
 *
 * Read/write the EnterpriseBadge's saved unified-login credentials.
 * Password lives in SECRET_FIELDS so it's AES-256-GCM encrypted at rest;
 * this endpoint hands it back in plaintext for the local UI to prefill
 * (Forge is single-user, runs on localhost — equivalent threat surface
 * to the user's own keychain). OTP is never persisted — it's TOTP.
 */

import { NextResponse } from 'next/server';
import { loadSettings, saveSettings } from '@/lib/settings';

export async function GET() {
  const s = loadSettings() as unknown as Record<string, unknown>;
  return NextResponse.json({
    username: (s.idpSavedUsername as string) || '',
    password: (s.idpSavedPassword as string) || '',
  });
}

export async function POST(req: Request) {
  let body: { username?: string; password?: string } = {};
  try { body = await req.json(); } catch { /* empty body */ }
  const username = String(body.username || '').trim();
  const password = String(body.password || '');
  if (!username || !password) {
    return NextResponse.json({ ok: false, error: 'username and password are required' }, { status: 400 });
  }
  const current = loadSettings() as unknown as Record<string, unknown>;
  saveSettings({ ...current, idpSavedUsername: username, idpSavedPassword: password } as never);
  return NextResponse.json({ ok: true });
}

export async function DELETE() {
  const current = loadSettings() as unknown as Record<string, unknown>;
  saveSettings({ ...current, idpSavedUsername: '', idpSavedPassword: '' } as never);
  return NextResponse.json({ ok: true });
}
