<?php

namespace App\Services;

use App\Enums\AiUsageStatus;
use App\Enums\AiUsageType;
use App\Models\AiUsage;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Throwable;

class AiUsageRecorder
{
    public function success(
        ?User $user,
        AiUsageType $type,
        ?array $input = null,
        ?array $output = null,
        ?string $provider = null,
        ?string $model = null,
        ?int $promptTokens = null,
        ?int $completionTokens = null,
        ?int $totalTokens = null,
        ?Model $related = null,
    ): AiUsage {
        return $this->record(
            user: $user,
            type: $type,
            status: AiUsageStatus::SUCCESS,
            input: $input,
            output: $output,
            provider: $provider,
            model: $model,
            promptTokens: $promptTokens,
            completionTokens: $completionTokens,
            totalTokens: $totalTokens,
            related: $related,
        );
    }

    public function failed(
        ?User $user,
        AiUsageType $type,
        Throwable $exception,
        ?array $input = null,
        ?Model $related = null,
    ): AiUsage {
        return $this->record(
            user: $user,
            type: $type,
            status: AiUsageStatus::FAILED,
            input: $input,
            errorMessage: Str::limit($exception::class.': '.$exception->getMessage(), 1000, ''),
            related: $related,
        );
    }

    private function record(
        ?User $user,
        AiUsageType $type,
        AiUsageStatus $status,
        ?array $input = null,
        ?array $output = null,
        ?string $provider = null,
        ?string $model = null,
        ?int $promptTokens = null,
        ?int $completionTokens = null,
        ?int $totalTokens = null,
        ?string $errorMessage = null,
        ?Model $related = null,
    ): AiUsage {
        return AiUsage::create([
            'user_id' => $user?->id,
            'type' => $type,
            'status' => $status,
            'input' => $input,
            'output' => $output,
            'provider' => $provider,
            'model' => $model,
            'prompt_tokens' => $promptTokens,
            'completion_tokens' => $completionTokens,
            'total_tokens' => $totalTokens,
            'error_message' => $errorMessage,
            'related_type' => $related ? $related::class : null,
            'related_id' => $related?->getKey(),
        ]);
    }
}
