<?php

declare(strict_types=1);

namespace App\Support;

use Illuminate\Http\Request;

/**
 * 写入 artisan down 的 except 列表（供 storage/framework/maintenance.php 在引导 Laravel 之前放行）。
 *
 * NOTE: 使用 --render 预渲染维护页时，未列入 except 的 URI 会在 index.php 最早阶段被 503 拦截，
 * 应用内中间件（含 AllowLivewireUpdateDuringSystemUpdateMaintenance）不会执行。
 */
final class DberpMaintenanceDownExceptPaths
{
    public const UPDATE_CENTER_PAGE_SLUG = 'host-system-update-center';

    /**
     * @return list<string>
     */
    public function paths(): array
    {
        $paths = [
            'livewire-*/update',
            'livewire-*/upload-file',
            'livewire-*/livewire.js',
            'livewire-*/livewire.min.js',
            'livewire-*/js/*',
            'livewire-*/css/*',
            'livewire-*/preview-file/*',
        ];

        $segment = self::UPDATE_CENTER_PAGE_SLUG;
        $paths[] = $segment;
        $paths[] = '*'.$segment;

        $panelPath = trim((string) config('dberp.admin.panel_path', ''), '/');

        if ($panelPath !== '') {
            $paths[] = $panelPath.'/'.$segment;
        }

        return array_values(array_unique($paths));
    }

    public function isSystemUpdateCenterRequest(Request $request): bool
    {
        $path = trim(str_replace('\\', '/', $request->path()), '/');
        $segment = self::UPDATE_CENTER_PAGE_SLUG;

        if ($path === '' || ! str_contains($path, $segment)) {
            return false;
        }

        return $path === $segment
            || str_ends_with($path, '/'.$segment);
    }
}
