<?php

namespace App\Http\Controllers\AiPortal;

use App\Models\CostCap;
use App\Services\AuditLogger;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;

class CostCapController extends Controller
{
    public function index(Request $request)
    {
        abort_unless($request->user()->isAdminOrAbove(), 403);

        $caps = CostCap::orderBy('scope')->orderBy('purpose')->orderBy('period')->get();

        // Annotate each cap with current period spend so the UI can show
        // "$2.34 of $5.00 used today" without a second roundtrip.
        $caps = $caps->map(function ($c) {
            $since = $c->period === CostCap::PERIOD_MONTH
                ? now()->startOfMonth()
                : now()->startOfDay();
            $q = DB::table('ai_costs')->where('called_at', '>=', $since);
            if ($c->scope === CostCap::SCOPE_PURPOSE && $c->purpose) {
                $q->where('purpose', $c->purpose);
            }
            $spent = (float) $q->sum('cost_usd');
            $limit = (float) $c->amount_usd;
            return [
                ...$c->toArray(),
                'spent_usd'    => round($spent, 4),
                'remaining_usd'=> round(max(0, $limit - $spent), 4),
                'percent'      => $limit > 0 ? round(min(100, ($spent / $limit) * 100), 1) : 0,
                'status'       => $spent >= $limit
                    ? 'exceeded'
                    : ($spent > 0.8 * $limit ? 'warning' : 'ok'),
            ];
        });

        return response()->json([
            'caps' => $caps,
            'available_purposes' => \App\Models\AiProvider::PURPOSES,
        ]);
    }

    public function store(Request $request)
    {
        abort_unless($request->user()->isAdminOrAbove(), 403);

        $data = $request->validate([
            'label'      => ['required', 'string', 'max:128'],
            'scope'      => ['required', 'in:fleet,purpose'],
            'purpose'    => ['nullable', 'required_if:scope,purpose', 'string', 'max:32'],
            'period'     => ['required', 'in:day,month'],
            'amount_usd' => ['required', 'numeric', 'min:0', 'max:100000'],
            'action'     => ['required', 'in:block,warn'],
            'enabled'    => ['nullable', 'boolean'],
        ]);

        $cap = CostCap::create([
            ...$data,
            'enabled'    => $data['enabled'] ?? true,
            'created_by' => $request->user()->id,
        ]);

        AuditLogger::log('user', (string) $request->user()->id, $request->user()->email,
            'ai.cost_cap_added', 'cost_cap', (string) $cap->id, $data, $request);

        return response()->json($cap, 201);
    }

    public function update(Request $request, CostCap $cap)
    {
        abort_unless($request->user()->isAdminOrAbove(), 403);

        $data = $request->validate([
            'label'      => ['nullable', 'string', 'max:128'],
            'scope'      => ['nullable', 'in:fleet,purpose'],
            'purpose'    => ['nullable', 'string', 'max:32'],
            'period'     => ['nullable', 'in:day,month'],
            'amount_usd' => ['nullable', 'numeric', 'min:0', 'max:100000'],
            'action'     => ['nullable', 'in:block,warn'],
            'enabled'    => ['nullable', 'boolean'],
        ]);

        $cap->fill(array_filter($data, fn ($v) => $v !== null))->save();

        AuditLogger::log('user', (string) $request->user()->id, $request->user()->email,
            'ai.cost_cap_updated', 'cost_cap', (string) $cap->id,
            ['changed' => array_keys($data)], $request);

        return response()->json($cap->fresh());
    }

    public function destroy(Request $request, CostCap $cap)
    {
        abort_unless($request->user()->isAdminOrAbove(), 403);
        AuditLogger::log('user', (string) $request->user()->id, $request->user()->email,
            'ai.cost_cap_removed', 'cost_cap', (string) $cap->id,
            ['label' => $cap->label], $request);
        $cap->delete();
        return response()->noContent();
    }
}
