<?php

declare(strict_types=1);

namespace App\Models;

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

/**
 * Платёжный шлюз (schema.sql table payment_gateways).
 * `config` хранится ЗАШИФРОВАННЫМ (Crypt::encrypt JSON {shop_id, secret_key}). Без RLS.
 *
 * @mixin IdeHelperPaymentGateway
 */
class PaymentGateway extends Model
{
    public $timestamps = false;

    protected $fillable = [
        'code', 'name', 'driver', 'legal_entity_id', 'config', 'is_active',
        'accepts_methods', 'min_amount_rub', 'max_amount_rub', 'sort_order',
    ];

    protected function casts(): array
    {
        return [
            'is_active' => 'boolean',
            'accepts_methods' => 'array',
            'min_amount_rub' => 'decimal:2',
            'max_amount_rub' => 'decimal:2',
        ];
    }

    /** Расшифрованные креденшелы шлюза; [] если config пустой/битый. */
    public function credentials(): array
    {
        if ($this->config === null || $this->config === '') {
            return [];
        }

        try {
            $decoded = Crypt::decrypt($this->config);
        } catch (\Throwable) {
            return [];
        }

        return is_array($decoded) ? $decoded : [];
    }
}
