<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Crypt;

class Provider extends Model
{
    protected $guarded = [];

    protected function casts(): array
    {
        return [
            'is_active' => 'boolean',
            'settings' => 'array',
            'last_health_at' => 'datetime',
            'timeout_seconds' => 'integer',
            'retry_attempts' => 'integer',
        ];
    }

    public function mappings()
    {
        return $this->hasMany(ProviderProductMapping::class);
    }

    public function logs()
    {
        return $this->hasMany(ProviderLog::class);
    }

    public function stockCodes()
    {
        return $this->hasMany(StockCode::class);
    }

    public function apiKey(): ?string
    {
        if ($this->api_key_env && env($this->api_key_env)) {
            return env($this->api_key_env);
        }

        return $this->encrypted_api_key ? Crypt::decryptString($this->encrypted_api_key) : null;
    }
}
