import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, AuthedRequest } from '@server/middleware/withAuth';
import { updateCouponSchema } from '@server/validators/coupons.validator';
import { getCoupon, updateCoupon, deleteCoupon } from '@server/services/coupons.service';
import { requirePlanFeature } from '@server/utils/features';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    await requireSection(req, 'coupons');
    await requirePlanFeature(req.session.restaurantId!, 'coupons');
    const { id } = await ctx.params;
    const coupon = await getCoupon(id, req.session.restaurantId!);
    return NextResponse.json({ coupon });
  })
);

export const PATCH = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    await requireSection(req, 'coupons', 'update');
    await requirePlanFeature(req.session.restaurantId!, 'coupons');
    const { id } = await ctx.params;
    const body = await req.json();
    const parsed = updateCouponSchema.parse(body);
    const coupon = await updateCoupon(id, req.session.restaurantId!, parsed);
    return NextResponse.json({ coupon });
  })
);

export const DELETE = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    await requireSection(req, 'coupons', 'delete');
    await requirePlanFeature(req.session.restaurantId!, 'coupons');
    const { id } = await ctx.params;
    await deleteCoupon(id, req.session.restaurantId!);
    return NextResponse.json({ success: true });
  })
);
