import { NextRequest, NextResponse } from 'next/server';
import { auditAction } from '@/features/foundation/audit-log/service';
import { unshareCustomerContact } from '@/features/crm/customers/server/service';
import { buildCrmSecurityContext } from '@/features/crm/security/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

type Params = {
  params: Promise<{ id: string; contactId: string; shareId: string }>;
};

export async function DELETE(_request: NextRequest, { params }: Params) {
  try {
    const { id, contactId, shareId } = await params;
    const { organization, session, membership } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmContactShareDelete
    });
    const accessContext = buildCrmSecurityContext({
      organizationId: organization.id,
      userId: session.user.id,
      membership
    });
    const removed = await unshareCustomerContact(
      id,
      contactId,
      shareId,
      organization.id,
      accessContext
    );

    await auditAction({
      organizationId: organization.id,
      userId: session.user.id,
      entityType: 'crm_contact_share',
      entityId: shareId,
      action: 'unshare',
      beforeData: {
        customerId: id,
        contactId,
        sharedUser: removed.sharedToUserId
      }
    });

    return NextResponse.json({
      success: true,
      message: 'Contact share removed successfully'
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    console.error(
      'DELETE /api/crm/customers/[id]/contacts/[contactId]/shares/[shareId] failed',
      error
    );
    return NextResponse.json({ message: 'Unable to remove contact share' }, { status: 500 });
  }
}
