import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, AuthedRequest } from '@server/middleware/withAuth';
import { getCouponAnalytics } from '@server/services/coupons.service';
import { ValidationError } from '@server/errors';
import { requirePlanFeature } from '@server/utils/features';

function parseDateParam(name: string, raw: string | null): string | undefined {
  if (!raw) return undefined;
  const t = Date.parse(raw);
  if (Number.isNaN(t)) throw new ValidationError(`Invalid ${name} date`);
  return new Date(t).toISOString();
}

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    await requireSection(req, 'coupons');
    await requirePlanFeature(req.session.restaurantId!, 'coupons');
    const url = new URL(req.url);
    const branchId = url.searchParams.get('branch_id') ?? undefined;
    const from = parseDateParam('from', url.searchParams.get('from'));
    const to = parseDateParam('to', url.searchParams.get('to'));
    if (from && to && Date.parse(from) > Date.parse(to)) {
      throw new ValidationError('`from` must be on or before `to`');
    }
    const result = await getCouponAnalytics({
      restaurantId: req.session.restaurantId!,
      branchId,
      from,
      to,
    });
    return NextResponse.json(result);
  })
);
