import { NextResponse } from 'next/server';
import { z } from 'zod';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import {
  getAiBudget,
  setAiBudget,
  currentPeriodTokens,
  periodBreakdown,
} from '@/lib/services/ai-budget.service';

const saveSchema = z.object({
  enabled: z.boolean().optional(),
  softCapTokens: z.number().int().nonnegative().max(100_000_000).optional(),
  hardCapTokens: z.number().int().nonnegative().max(100_000_000).optional(),
  period: z.enum(['day', 'week', 'month']).optional(),
});

export const GET = withAuth(
  withPermission('admin', 'manage_settings', async (req, ctx) => {
    try {
      const [budget, used, breakdown] = await Promise.all([
        getAiBudget(ctx.portId),
        currentPeriodTokens(ctx.portId),
        periodBreakdown(ctx.portId),
      ]);
      return NextResponse.json({ data: { budget, used, breakdown } });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const PUT = withAuth(
  withPermission('admin', 'manage_settings', async (req, ctx) => {
    try {
      const body = await parseBody(req, saveSchema);
      const next = await setAiBudget(ctx.portId, body, ctx.userId);
      return NextResponse.json({ data: next });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
