import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { requirePlanFeature } from '@server/utils/features';
import { previewSchema } from '@server/validators/marketing.validator';
import { previewSegmentCount, previewSegmentSample } from '@server/services/marketing/segments.service';
import { scopeAudienceRules } from '@server/utils/branch-access';

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(previewSchema, async (req) => {
      const restaurantId = req.session.restaurantId!;
      await requireSection(req, 'marketing');
      await requirePlanFeature(restaurantId, 'marketing');
      const body = req.parsedBody as { rules: { branchIds?: string[] | null } & Record<string, unknown>; sample?: boolean };
      // Scope rules.branchIds against the caller's effective branch BEFORE
      // the audience compiler turns them into `o.branch_id = ANY(...)`.
      // Without this, a pinned-staff user could preview sibling-branch
      // customer counts/samples just by typing the sibling UUIDs into the
      // request body — bypassing every other branch filter we apply.
      const rules = scopeAudienceRules(req.session, body.rules);
      const [count, sample] = await Promise.all([
        previewSegmentCount(restaurantId, rules),
        body.sample === false
          ? Promise.resolve([])
          : previewSegmentSample(restaurantId, rules, 25),
      ]);
      return NextResponse.json({ count, sample });
    })
  )
);
