<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class AiProvider extends Model
{
    protected $fillable = [
        'name',
        'code',
        'api_key',
        'api_url',
        'model',
        'is_enabled',
        'is_default',
        'capabilities',
        'max_tokens',
        'temperature',
        'max_steps',
    ];

    protected $casts = [
        'is_enabled' => 'boolean',
        'is_default' => 'boolean',
        'capabilities' => 'array',
        'max_tokens' => 'integer',
        'temperature' => 'decimal:2',
        'max_steps' => 'integer',
    ];

    /**
     * Set this provider as default, unsetting others.
     */
    public function setAsDefault(): void
    {
        static::query()->update(['is_default' => false]);
        $this->update(['is_default' => true]);
    }

    /**
     * Get the default provider.
     */
    public static function getDefault(): ?self
    {
        return static::where('is_enabled', true)
            ->where('is_default', true)
            ->first();
    }

    /**
     * Get all enabled providers.
     */
    public static function getEnabled()
    {
        return static::where('is_enabled', true)->get();
    }

    /**
     * Get the API key (masked for display).
     */
    public function getMaskedApiKeyAttribute(): string
    {
        if (empty($this->api_key)) {
            return '';
        }

        if (strlen($this->api_key) <= 8) {
            return str_repeat('*', strlen($this->api_key));
        }

        return substr($this->api_key, 0, 4).str_repeat('*', strlen($this->api_key) - 8).substr($this->api_key, -4);
    }
}
