<?php

namespace App\Services\AI;

use App\Models\AI\AiUsageLog;
use Illuminate\Support\Facades\Auth;

abstract class BaseAiProvider implements AiProviderInterface
{
    protected $config;

    public function __construct(array $config = [])
    {
        $this->config = $config;
    }

    /**
     * Log the AI usage to the database.
     */
    protected function logUsage(array $data): void
    {
        try {
            AiUsageLog::create([
                'user_id' => Auth::id(),
                'provider' => $this->getIdentifier(),
                'model' => $data['model'] ?? 'unknown',
                'prompt' => $data['prompt'] ?? null,
                'response' => $data['response'] ?? null,
                'prompt_tokens' => $data['usage']['prompt_tokens'] ?? 0,
                'completion_tokens' => $data['usage']['completion_tokens'] ?? 0,
                'total_tokens' => $data['usage']['total_tokens'] ?? 0,
                'estimated_cost' => $this->calculateCost($data),
                'status' => $data['status'] ?? 'success',
                'error_message' => $data['error'] ?? null,
                'metadata' => $data['metadata'] ?? null,
            ]);
        } catch (\Exception $e) {
            \Log::error('Failed to log AI usage: '.$e->getMessage());
        }
    }

    /**
     * Abstract cost calculation, to be implemented by each provider.
     */
    protected function calculateCost(array $data): float
    {
        // Default implementation, can be overridden
        return 0.0;
    }
}
