<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Contracts\Encryption\DecryptException;

class AiProvider extends Model
{
    protected $fillable = [
        'provider_key', 'provider_name', 'api_endpoint', 'api_key', 
        'default_model', 'notes', 'priority', 'is_enabled', 'is_active'
    ];

    protected $casts = [
        'is_enabled' => 'boolean',
        'is_active' => 'boolean',
    ];

    // --- Automatically encrypt the API key when setting it ---
    public function setApiKeyAttribute($value)
    {
        if (!empty($value)) {
            $this->attributes['api_key'] = Crypt::encryptString($value);
        }
    }

    // --- Automatically decrypt the API key when getting it ---
    public function getApiKeyAttribute($value)
    {
        if (empty($value)) {
            return null;
        }
        try {
            return Crypt::decryptString($value);
        } catch (DecryptException $e) {
            // Handle cases where decryption fails (e.g., old unencrypted data)
            return 'Error: Could not decrypt key.';
        }
    }
}