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 { getCampaign, getCampaignReport } from '@server/services/marketing/campaigns.service';
import { effectiveBranchId, loadAccessibleOrThrow } from '@server/utils/branch-access';
import { NotFoundError } from '@server/errors';

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;
    // Pre-flight visibility check on the branch-scoped getter — without it
    // a pinned user could read a sibling branch's send-stats report by ID.
    // loadAccessibleOrThrow returns 403 for sibling-branch IDs and 404 for
    // genuinely missing IDs.
    await loadAccessibleOrThrow(
      await getCampaign(restaurantId, id, effectiveBranchId(req.session)),
      () => getCampaign(restaurantId, id, null),
      'Campaign',
    );
    const report = await getCampaignReport(restaurantId, id);
    if (!report) throw new NotFoundError('Campaign');
    return NextResponse.json(report);
  })
);
