/**
 * DELETE /api/orgs/[id]/invites/[inviteId] — revoke an invite (admin+).
 */

import { requireSession, requireFreshMembership } from '@/lib/auth.js';
import { requireRole } from '@/lib/authz.js';
import { getMembership } from '@/lib/org.js';
import { revokeInvite } from '@/lib/invites.js';
import { getDb } from '@/lib/db.js';

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

export async function DELETE(req, { params }) {
  try {
    const { id: orgId, inviteId } = await params;
    const session = await requireSession(req);
    await requireFreshMembership(session, orgId);
    const membership = getMembership(session.user_id, orgId);
    if (!membership) return Response.json({ error: 'insufficient_role' }, { status: 403 });
    requireRole({ ...session, org_id: orgId, role: membership.role }, 'admin', orgId);

    // The invite must belong to this org (no cross-org revoke).
    const row = getDb().prepare('SELECT org_id, email, token_hash FROM org_invites WHERE id = ?').get(inviteId);
    if (!row || row.org_id !== orgId) {
      return Response.json({ error: 'not_found' }, { status: 404 });
    }

    revokeInvite(inviteId, session.user_id);

    // Best-effort cloud revoke (owner machine). The cloud row has its OWN uuid id
    // (the local id is not a uuid), so we key on the same fields used at create —
    // token_hash for a link, org_id+email for an email invite — and hard-delete
    // it so a redeem RPC can no longer find it. Non-fatal; integration-deferred.
    try {
      const { isSharedCloudReady, getSharedCloudAdmin } = await import('@/lib/shared-cloud.js');
      if (isSharedCloudReady()) {
        const filters = row.token_hash
          ? { token_hash: row.token_hash }
          : { org_id: orgId, email: row.email };
        await getSharedCloudAdmin().delete('org_invites', { filters }).catch(() => {});
      }
    } catch { /* non-fatal */ }

    return Response.json({ ok: true });
  } catch (err) {
    if (err.status) return Response.json({ error: err.error }, { status: err.status });
    console.error('DELETE /api/orgs/[id]/invites/[inviteId] error:', err);
    return Response.json({ error: 'Failed to revoke invite' }, { status: 500 });
  }
}
