import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { updateAiConfigSchema } from '@server/validators/ai-config.validator';
import { ensureAiConfig, updateAiConfig } from '@server/services/ai-config.service';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId, branchId } = req.session;
    await requireSection(req, 'ai_config');
    const url = new URL(req.url);
    const bId = url.searchParams.get('branch_id') ?? branchId ?? undefined;
    const config = await ensureAiConfig(restaurantId!, bId);
    return NextResponse.json({ config });
  })
);

export const PATCH = withErrorHandler(
  withAuth(
    withValidationAuthed(updateAiConfigSchema, async (req) => {
      await requireSection(req, 'ai_config', 'update');
      const url = new URL(req.url);
      const bId = url.searchParams.get('branch_id') ?? req.session.branchId ?? undefined;
      const config = await updateAiConfig(req.session.restaurantId!, req.parsedBody as Record<string, unknown>, bId);
      return NextResponse.json({ config });
    })
  )
);
