import { decideApprovalRequest, getApprovalRequest } from '@/lib/approvals.js';
import { requireSession } from '@/lib/auth.js';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

function requireAdmin(session) {
  if (session.role !== 'admin' && session.role !== 'owner') {
    throw { status: 403, error: 'forbidden' };
  }
}

export async function GET(req, { params }) {
  try {
    await requireSession(req);
    const { id } = await params;
    const approval = getApprovalRequest(id);
    if (!approval) return new Response('Approval request not found', { status: 404 });
    return Response.json({ ok: true, approval });
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    throw err;
  }
}

export async function PATCH(req, { params }) {
  const { id } = await params;
  let body;
  try {
    body = await req.json();
  } catch {
    return new Response('Invalid JSON', { status: 400 });
  }
  const decision = body?.decision;
  if (!['approved', 'denied'].includes(decision)) {
    return new Response('decision must be approved or denied', { status: 400 });
  }
  try {
    const session = await requireSession(req);
    requireAdmin(session);
    const approval = decideApprovalRequest(id, decision, { approved_by: body.approved_by || session.user_id || 'owner' });
    return Response.json({ ok: true, approval });
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    const status = /not found/i.test(err.message) ? 404 : 409;
    return new Response(err.message, { status });
  }
}
