import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { requirePlanFeature } from '@server/utils/features';
import { createSegmentSchema } from '@server/validators/marketing.validator';
import { listSegments, createSegment } from '@server/services/marketing/segments.service';
import { effectiveBranchId, isBranchPinned, scopeAudienceRules } from '@server/utils/branch-access';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const restaurantId = req.session.restaurantId!;
    await requireSection(req, 'marketing');
    await requirePlanFeature(restaurantId, 'marketing');
    // Owners viewing "All branches" see every segment in the restaurant;
    // active-branch owners and pinned staff see (branch-wide ∪ this branch).
    const segments = await listSegments(restaurantId, effectiveBranchId(req.session));
    return NextResponse.json({ segments });
  })
);

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(createSegmentSchema, async (req) => {
      const restaurantId = req.session.restaurantId!;
      await requireSection(req, 'marketing', 'create');
      await requirePlanFeature(restaurantId, 'marketing');
      const body = req.parsedBody as { name: string; description?: string | null; rules?: { branchIds?: string[] | null } & Record<string, unknown> };
      // Pinned staff can ONLY create segments scoped to their pinned branch;
      // they may not author restaurant-wide audiences. Owners default to the
      // currently-active branch (or null when "All branches" is selected) so
      // a segment created from a branch view is automatically scoped.
      const branchId = isBranchPinned(req.session)
        ? req.session.pinnedBranchId!
        : (req.session.branchId ?? null);
      // Re-validate rules.branchIds — the segment's row-level branch_id
      // above is one half of the story; the rules JSON is what the
      // audience compiler turns into `o.branch_id = ANY(...)`, so a
      // pinned user could otherwise pin the row to their branch but
      // still TARGET sibling-branch customers via the rules payload.
      const rules = scopeAudienceRules(req.session, body.rules ?? {});
      const segment = await createSegment(restaurantId, {
        name: body.name,
        description: body.description ?? null,
        rules,
        createdBy: req.session.userId,
        branchId,
      });
      return NextResponse.json({ segment }, { status: 201 });
    })
  )
);
