<?php

declare(strict_types=1);

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,
            ],
        ]);
    }
}
