import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { updateWebhookSchema } from '@server/validators/webhooks.validator';
import { getWebhook, updateWebhook, deleteWebhook } from '@server/services/webhooks.service';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    const { id } = await ctx.params;
    const webhook = await getWebhook(id, req.session.restaurantId!);
    return NextResponse.json({ webhook });
  })
);

export const PATCH = withErrorHandler(
  withAuth(
    withValidationAuthed(updateWebhookSchema, async (req, ctx: RouteContext) => {
      const { id } = await ctx.params;
      const webhook = await updateWebhook(id, req.session.restaurantId!, req.parsedBody as Record<string, unknown>);
      return NextResponse.json({ webhook });
    })
  )
);

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