<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;

/**
 * 宿主官方授权快照（单例表 host_system_authorizations）。
 *
 * @property bool $authorized
 * @property string|null $product_code
 * @property string|null $site_no
 * @property string|null $license_no
 * @property string|null $license_holder
 * @property string|null $service_status
 * @property Carbon|null $expires_at
 * @property array<string, mixed>|null $bound_domains
 * @property array<string, mixed>|null $entitlements
 * @property string|null $last_sync_status
 * @property string|null $last_sync_message
 * @property string|null $last_sync_error_code
 * @property Carbon|null $last_synced_at
 * @property array<string, mixed>|null $raw_snapshot
 */
class HostSystemAuthorization extends Model
{
    public const SINGLETON_KEY = 'default';

    protected $table = 'host_system_authorizations';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'singleton_key',
        'authorized',
        'product_code',
        'site_no',
        'license_no',
        'license_holder',
        'service_status',
        'expires_at',
        'bound_domains',
        'entitlements',
        'last_sync_status',
        'last_sync_message',
        'last_sync_error_code',
        'last_synced_at',
        'raw_snapshot',
    ];

    protected function casts(): array
    {
        return [
            'authorized' => 'boolean',
            'expires_at' => 'datetime',
            'bound_domains' => 'array',
            'entitlements' => 'array',
            'last_synced_at' => 'datetime',
            'raw_snapshot' => 'array',
        ];
    }

    public static function singleton(): self
    {
        /** @var self $record */
        $record = self::query()->firstOrCreate(
            ['singleton_key' => self::SINGLETON_KEY],
            [
                'authorized' => false,
                'product_code' => 'dberp',
            ],
        );

        return $record;
    }
}
