import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { promoteContactToPrimary } from '@/lib/services/clients.service';

/**
 * Phase 3d - promote a non-primary `client_contacts` row to primary,
 * demoting the prior primary for the same channel inside a single
 * transaction. Surfaces from the "[EOI] Set as primary" action on the
 * client detail panel, and from the EOI dialog's "Set as default for
 * future docs" toggle (though that path calls the service directly via
 * `eoi-overrides.service`).
 */
export const POST = withAuth(
  withPermission('clients', 'edit', async (_req, ctx, params) => {
    try {
      const contact = await promoteContactToPrimary(params.contactId!, params.id!, ctx.portId, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: contact });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
