<?php

namespace App\Domains\AI\Actions;

use App\Domains\AI\Models\AiUsageDaily;
use App\Domains\Tenancy\Models\Tenant;

class RecordAiUsageDailyAction
{
    public function execute(
        Tenant $tenant,
        string $featureKey,
        ?int $tokensInput = null,
        ?int $tokensOutput = null,
        ?float $costAmount = null,
    ): void {
        $usage = AiUsageDaily::query()->firstOrCreate(
            [
                'tenant_id' => $tenant->getKey(),
                'feature_key' => $featureKey,
                'usage_date' => now()->toDateString(),
            ],
            [
                'requests_count' => 0,
                'tokens_input' => 0,
                'tokens_output' => 0,
                'estimated_cost' => 0,
            ]
        );

        $usage->increment('requests_count');
        $usage->increment('tokens_input', $tokensInput ?? 0);
        $usage->increment('tokens_output', $tokensOutput ?? 0);

        if ($costAmount) {
            $usage->estimated_cost = (float) $usage->estimated_cost + $costAmount;
            $usage->save();
        }
    }
}
