import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, AuthedRequest } from '@server/middleware/withAuth';
import { createCouponSchema } from '@server/validators/coupons.validator';
import { listCoupons, createCoupon } from '@server/services/coupons.service';
import { requirePlanFeature } from '@server/utils/features';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId, branchId } = req.session;
    await requireSection(req, 'coupons');
    await requirePlanFeature(restaurantId!, 'coupons');
    const url = new URL(req.url);
    const p = url.searchParams;

    const result = await listCoupons({
      restaurantId: restaurantId!,
      branchId: p.get('branch_id') ?? branchId ?? undefined,
      status: (p.get('status') as 'active' | 'archived' | null) ?? undefined,
      search: p.get('search') ?? undefined,
      page: parseInt(p.get('page') ?? '1', 10),
      limit: parseInt(p.get('limit') ?? '50', 10),
    });

    return NextResponse.json(result);
  })
);

export const POST = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    await requireSection(req, 'coupons', 'create');
    await requirePlanFeature(req.session.restaurantId!, 'coupons');
    const body = await req.json();
    const parsed = createCouponSchema.parse(body);
    const coupon = await createCoupon(req.session.restaurantId!, req.session.branchId ?? null, parsed);
    return NextResponse.json({ coupon }, { status: 201 });
  })
);
