<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * 后台站点 / 主站接入配置（{@see $table admin_sites}）。
 *
 * `code` 对外即 JWT 与钱包回调中的 `site_code`，创建后不可修改。
 */
final class AdminSite extends Model
{
    protected $table = 'admin_sites';

    protected $fillable = [
        'code',
        'name',
        'currency_code',
        'status',
        'is_default',
        'extra_json',
        'wallet_api_url',
        'wallet_debit_path',
        'wallet_credit_path',
        'wallet_balance_path',
        'wallet_api_key_encrypted',
        'sso_jwt_secret_encrypted',
        'wallet_timeout_seconds',
        'iframe_allowed_origins',
        'lottery_h5_base_url',
        'notes',
    ];

    protected function casts(): array
    {
        return [
            'status' => 'integer',
            'is_default' => 'boolean',
            'extra_json' => 'array',
            'iframe_allowed_origins' => 'array',
            'wallet_timeout_seconds' => 'integer',
        ];
    }

    public function isEnabled(): bool
    {
        return (int) $this->status === 1;
    }

    public function decryptedSsoJwtSecret(): ?string
    {
        return $this->decryptSecret($this->sso_jwt_secret_encrypted);
    }

    public function decryptedWalletApiKey(): ?string
    {
        return $this->decryptSecret($this->wallet_api_key_encrypted);
    }

    private function decryptSecret(?string $encrypted): ?string
    {
        if (! is_string($encrypted) || $encrypted === '') {
            return null;
        }

        try {
            return decrypt($encrypted);
        } catch (\Throwable) {
            return null;
        }
    }
}
