import { NextResponse } from 'next/server';
import { verifyAdmin, getAdminPassword } from '@/lib/password';
import { createApiKey, listApiKeys } from '@/lib/api-keys';
import { isAuthenticated } from '@/lib/api-auth';
import { isValidToken } from '@/app/api/auth/verify/route';

function isDev(): boolean {
  return process.env.NODE_ENV !== 'production' || process.env.FORGE_DEV === '1';
}

/** Reads require an authenticated caller (browser session, valid key, or dev). */
async function canRead(req: Request): Promise<boolean> {
  return isDev() || (await isAuthenticated(req)) || isValidToken(req);
}

// GET /api/auth/keys — list keys (no secrets)
export async function GET(req: Request) {
  if (!(await canRead(req))) return NextResponse.json({ error: 'unauthorized' }, { status: 401 });
  return NextResponse.json({ keys: listApiKeys(), adminConfigured: !!getAdminPassword() });
}

// POST /api/auth/keys — mint a key; requires the admin password
export async function POST(req: Request) {
  const body = await req.json().catch(() => ({}));
  const { name, adminPassword } = body as { name?: string; adminPassword?: string };

  if (!getAdminPassword()) {
    return NextResponse.json({ error: 'Set an admin password first' }, { status: 400 });
  }
  if (!verifyAdmin(adminPassword || '')) {
    return NextResponse.json({ error: 'Invalid admin password' }, { status: 403 });
  }

  const { key, record } = createApiKey(name || 'agent key');
  return NextResponse.json({ key, record });
}
