/**
 * PATCH /api/orgs/[id]/members/[userId]/role — change member role (owner only)
 */

import { requireSession, requireFreshMembership } from '@/lib/auth.js';
import { requireRole } from '@/lib/authz.js';
import { changeRole, getMembership } from '@/lib/org.js';
import { appendComplianceAudit, ComplianceActions, requestIp, requestUserAgent } from '@/lib/compliance-audit.js';

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

export async function PATCH(req, { params }) {
  let body;
  try {
    body = await req.json();
  } catch {
    return Response.json({ error: 'Invalid JSON' }, { status: 400 });
  }

  try {
    const { id: orgId, userId } = await params;
    const session = await requireSession(req);

    // RD-1: owner privilege escalation — verify membership is still active (live check).
    await requireFreshMembership(session, orgId);

    // Only owners may change roles.
    const callerMembership = getMembership(session.user_id, orgId);
    if (!callerMembership) {
      return Response.json({ error: 'insufficient_role' }, { status: 403 });
    }
    requireRole({ ...session, role: callerMembership.role }, 'owner', orgId);

    const { role } = body;
    if (!role) {
      return Response.json({ error: 'role is required' }, { status: 400 });
    }

    changeRole(orgId, userId, role);

    try {
      appendComplianceAudit({
        user_id: session.user_id,
        org_id: orgId,
        action: ComplianceActions.ORG_MEMBER_ROLE_CHANGED,
        action_target_id: userId,
        action_target_type: 'user',
        status: 'success',
        summary: `Role of user ${userId} changed to ${role} in org ${orgId}`,
        meta: { org_id: orgId, user_id: userId, new_role: role },
        ip: requestIp(req),
        user_agent: requestUserAgent(req),
      });
    } catch (auditErr) {
      console.error('[orgs/members/role] audit write failed:', auditErr.message);
    }

    return Response.json({ ok: true, org_id: orgId, user_id: userId, role });
  } catch (err) {
    if (err.status) {
      return Response.json({ error: err.error }, { status: err.status });
    }
    if (err.message?.includes('Invalid role') || err.message?.includes('last owner')) {
      return Response.json({ error: err.message }, { status: 400 });
    }
    console.error('PATCH /api/orgs/[id]/members/[userId]/role error:', err);
    return Response.json({ error: 'Failed to change role' }, { status: 500 });
  }
}
