import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { createWebhookSchema } from '@server/validators/webhooks.validator';
import { listWebhooks, createWebhook } from '@server/services/webhooks.service';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const webhooks = await listWebhooks(req.session.restaurantId!);
    return NextResponse.json({ webhooks });
  })
);

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(createWebhookSchema, async (req) => {
      const webhook = await createWebhook(req.session.restaurantId!, req.parsedBody as Record<string, unknown>);
      return NextResponse.json({ webhook }, { status: 201 });
    })
  )
);
