<?php

declare(strict_types=1);

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