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 { createApiKeySchema } from '@server/validators/api-keys.validator';
import { listApiKeys, createApiKey } from '@server/services/api-keys.service';

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

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