import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, AuthedRequest } from '@server/middleware/withAuth';
import { requirePlanFeature } from '@server/utils/features';
import { listLinkedActiveCampaigns, getSegment } from '@server/services/marketing/segments.service';
import { effectiveBranchId, loadAccessibleOrThrow } from '@server/utils/branch-access';

/**
 * Pre-check used by the Audiences page before showing the delete confirm
 * prompt — returns the still-active (draft/scheduled/sending) campaigns
 * that reference this segment so the operator sees, up front, how many
 * campaigns will be auto-detached and continue with a snapshot of the
 * rules. Completed/cancelled/failed campaigns are intentionally excluded.
 *
 * Branch isolation: pre-flight the segment under the caller's effective
 * branch — without this a pinned-staff user could enumerate sibling
 * branches' active campaigns by guessing segment UUIDs (the linked-list
 * helper itself has no branch filter).
 */
export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    const restaurantId = req.session.restaurantId!;
    await requireSection(req, 'marketing');
    await requirePlanFeature(restaurantId, 'marketing');
    const { id } = await ctx.params;
    await loadAccessibleOrThrow(
      await getSegment(restaurantId, id, effectiveBranchId(req.session)),
      () => getSegment(restaurantId, id, null),
      'Segment',
    );
    const campaigns = await listLinkedActiveCampaigns(restaurantId, id, effectiveBranchId(req.session));
    return NextResponse.json({ campaigns });
  })
);
