/**
 * DELETE /api/orgs/[id]/members/[userId] — remove a member (requires admin+)
 */

import { requireSession, requireFreshMembership } from '@/lib/auth.js';
import { requireRole } from '@/lib/authz.js';
import { removeMember, getMembership } from '@/lib/org.js';

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

export async function DELETE(req, { params }) {
  try {
    const { id: orgId, userId } = await params;
    const session = await requireSession(req);
    await requireFreshMembership(session, orgId);

    const callerMembership = getMembership(session.user_id, orgId);
    if (!callerMembership) {
      return Response.json({ error: 'insufficient_role' }, { status: 403 });
    }
    requireRole({ ...session, role: callerMembership.role }, 'admin', orgId);

    removeMember(orgId, userId);
    return Response.json({ ok: true });
  } catch (err) {
    if (err.status) {
      return Response.json({ error: err.error }, { status: err.status });
    }
    if (err.message?.includes('last owner')) {
      return Response.json({ error: err.message }, { status: 409 });
    }
    console.error('DELETE /api/orgs/[id]/members/[userId] error:', err);
    return Response.json({ error: 'Failed to remove member' }, { status: 500 });
  }
}
