<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Services\SupportCenter;

use App\Models\HostSystemUpdateExecution;

/**
 * 生成 file/env 备份 manifest（不含 .env 明文与密钥）。
 */
final class HostSystemUpdateBackupManifestBuilder
{
    public const CHECKSUM_ALGORITHM = 'sha256';

    /**
     * @param  list<string>  $backedUpPaths
     * @param  list<string>  $missingPaths
     * @param  array<string, array{size: int, checksum: string}>  $fileMeta
     * @return array<string, mixed>
     */
    public function buildFileSnapshotManifest(
        HostSystemUpdateExecution $execution,
        array $backedUpPaths,
        array $missingPaths,
        array $fileMeta,
    ): array {
        $files = [];

        foreach ($backedUpPaths as $path) {
            $meta = $fileMeta[$path] ?? null;

            if (! is_array($meta)) {
                continue;
            }

            $files[] = [
                'path' => $path,
                'size' => $meta['size'],
                'checksum' => $meta['checksum'],
            ];
        }

        $sanitized = SupportCenterSnapshotSanitizer::sanitize([
            'execution_no' => $execution->execution_no,
            'product_code' => $execution->product_code,
            'from_version' => $execution->from_version,
            'from_update_version' => $execution->from_update_version,
            'to_version' => $execution->to_version,
            'to_update_version' => $execution->to_update_version,
            'created_at' => now()->utc()->toIso8601String(),
            'checksum_algorithm' => self::CHECKSUM_ALGORITHM,
        ]);

        return array_merge($sanitized, [
            'backed_up_paths' => $backedUpPaths,
            'missing_paths' => $missingPaths,
            'files' => $files,
        ]);
    }

    /**
     * @return array<string, mixed>
     */
    public function buildEnvSnapshotManifest(
        HostSystemUpdateExecution $execution,
        int $size,
        string $checksum,
    ): array {
        return SupportCenterSnapshotSanitizer::sanitize([
            'execution_no' => $execution->execution_no,
            'product_code' => $execution->product_code,
            'from_version' => $execution->from_version,
            'from_update_version' => $execution->from_update_version,
            'to_version' => $execution->to_version,
            'to_update_version' => $execution->to_update_version,
            'created_at' => now()->utc()->toIso8601String(),
            'checksum_algorithm' => self::CHECKSUM_ALGORITHM,
            'env_snapshot' => [
                'path' => '.env',
                'size' => $size,
                'checksum' => $checksum,
                'content_redacted' => true,
            ],
        ]);
    }
}
