<?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;
use App\Models\HostSystemUpdateExecutionLog;
use Illuminate\Support\Carbon;

/**
 * 系统更新执行步骤日志（脱敏上下文，不含密钥）。
 */
final class HostSystemUpdateExecutionLogger
{
    public function logTransition(
        HostSystemUpdateExecution $execution,
        string $step,
        string $message,
        ?array $context = null,
    ): HostSystemUpdateExecutionLog {
        return $this->writeLog(
            execution: $execution,
            step: $step,
            status: HostSystemUpdateExecutionLog::STATUS_TRANSITION,
            message: $message,
            context: $context,
        );
    }

    public function logStepStarted(
        HostSystemUpdateExecution $execution,
        string $step,
        string $message,
        ?array $context = null,
    ): HostSystemUpdateExecutionLog {
        return $this->writeLog(
            execution: $execution,
            step: $step,
            status: HostSystemUpdateExecutionLog::STATUS_STARTED,
            message: $message,
            context: $context,
            startedAt: now()->utc(),
        );
    }

    public function logStepCompleted(
        HostSystemUpdateExecution $execution,
        string $step,
        string $message,
        ?array $context = null,
        ?Carbon $startedAt = null,
    ): HostSystemUpdateExecutionLog {
        $finishedAt = now()->utc();

        return $this->writeLog(
            execution: $execution,
            step: $step,
            status: HostSystemUpdateExecutionLog::STATUS_COMPLETED,
            message: $message,
            context: $context,
            startedAt: $startedAt,
            finishedAt: $finishedAt,
            durationMs: $this->durationMs($startedAt, $finishedAt),
        );
    }

    public function logStepFailed(
        HostSystemUpdateExecution $execution,
        string $step,
        string $message,
        string $errorCode,
        ?string $errorMessage = null,
        ?array $context = null,
        ?Carbon $startedAt = null,
    ): HostSystemUpdateExecutionLog {
        $finishedAt = now()->utc();

        return $this->writeLog(
            execution: $execution,
            step: $step,
            status: HostSystemUpdateExecutionLog::STATUS_FAILED,
            message: $message,
            context: $context,
            startedAt: $startedAt,
            finishedAt: $finishedAt,
            durationMs: $this->durationMs($startedAt, $finishedAt),
            errorCode: $errorCode,
            errorMessage: $errorMessage ?? $message,
        );
    }

    /**
     * @param  array<string, mixed>|null  $context
     */
    private function writeLog(
        HostSystemUpdateExecution $execution,
        string $step,
        string $status,
        string $message,
        ?array $context = null,
        ?Carbon $startedAt = null,
        ?Carbon $finishedAt = null,
        ?int $durationMs = null,
        ?string $errorCode = null,
        ?string $errorMessage = null,
    ): HostSystemUpdateExecutionLog {
        $log = new HostSystemUpdateExecutionLog([
            'execution_id' => $execution->getKey(),
            'step' => $step,
            'status' => $status,
            'message' => $message,
            'context' => $this->sanitizeContext($context),
            'started_at' => $startedAt,
            'finished_at' => $finishedAt,
            'duration_ms' => $durationMs,
            'error_code' => $errorCode,
            'error_message' => $errorMessage,
        ]);
        $log->save();

        return $log;
    }

    /**
     * @param  array<string, mixed>|null  $context
     * @return array<string, mixed>|null
     */
    private function sanitizeContext(?array $context): ?array
    {
        if ($context === null || $context === []) {
            return null;
        }

        $sanitized = SupportCenterSnapshotSanitizer::sanitize($context);

        foreach ($sanitized as $key => $value) {
            if (! is_string($key) || ! is_string($value)) {
                continue;
            }

            if ($this->isPathKey($key)) {
                $sanitized[$key] = $this->maskStoragePath($value);
            }
        }

        return $sanitized === [] ? null : $sanitized;
    }

    private function isPathKey(string $key): bool
    {
        $normalized = strtolower($key);

        return str_contains($normalized, 'path')
            || str_contains($normalized, 'file')
            || str_contains($normalized, 'directory');
    }

    private function maskStoragePath(string $path): string
    {
        $normalized = str_replace('\\', '/', trim($path));

        if ($normalized === '') {
            return '';
        }

        $storageRoot = str_replace('\\', '/', storage_path());
        $basePath = str_replace('\\', '/', base_path());

        if (str_starts_with($normalized, $storageRoot.'/')) {
            return 'storage/'.substr($normalized, strlen($storageRoot) + 1);
        }

        if (str_starts_with($normalized, $basePath.'/')) {
            return substr($normalized, strlen($basePath) + 1);
        }

        if (preg_match('/^[A-Za-z]:[\/\\\\]/', $path) === 1 || str_starts_with($normalized, '/')) {
            return SupportCenterAuditLogger::maskIdentifier(basename($normalized));
        }

        return $normalized;
    }

    private function durationMs(?Carbon $startedAt, Carbon $finishedAt): ?int
    {
        if ($startedAt === null) {
            return null;
        }

        return max(0, (int) $finishedAt->diffInMilliseconds($startedAt));
    }
}
