<?php

declare(strict_types=1);

namespace App\Services\SupportCenter;

use App\Enums\SupportCenter\SupportCenterCheckSeverity;

/**
 * Support Center 自检报告聚合。
 */
final class SupportCenterCheckReport
{
    /**
     * @param  list<SupportCenterCheckRow>  $rows
     */
    public function __construct(
        private readonly array $rows,
    ) {}

    /**
     * @return list<SupportCenterCheckRow>
     */
    public function rows(): array
    {
        return $this->rows;
    }

    public function hasErrors(): bool
    {
        foreach ($this->rows as $row) {
            if ($row->severity === SupportCenterCheckSeverity::Error) {
                return true;
            }
        }

        return false;
    }

    public function hasWarnings(): bool
    {
        foreach ($this->rows as $row) {
            if ($row->severity === SupportCenterCheckSeverity::Warn) {
                return true;
            }
        }

        return false;
    }

    /**
     * 安装包是否具备官方 Open Host 接入能力（不含远程连通性）。
     */
    public function isPackageReady(): bool
    {
        foreach ($this->rows as $row) {
            if ($row->severity !== SupportCenterCheckSeverity::Error) {
                continue;
            }

            if (in_array($row->id, self::packageBlockingCheckIds(), true)) {
                return false;
            }
        }

        return true;
    }

    /**
     * @return list<string>
     */
    public function reasonCodes(): array
    {
        $codes = [];

        foreach ($this->rows as $row) {
            if ($row->reasonCode === null || $row->reasonCode === '') {
                continue;
            }

            $codes[] = $row->reasonCode;
        }

        return array_values(array_unique($codes));
    }

    /**
     * @return list<string>
     */
    private static function packageBlockingCheckIds(): array
    {
        return [
            'support_center_enabled',
            'stub_mode_disabled',
            'product_code_dberp',
            'base_url_configured',
            'host_token_resolved',
            'release_credentials',
        ];
    }
}
