<?php

namespace App\Services\Sync;

class SyncResult
{
    public function __construct(
        public readonly bool $ok,
        public readonly string $message,
        public readonly array $counts = [],
        public readonly ?int $durationMs = null,
        public readonly ?string $error = null,
    ) {}

    public static function success(string $message, array $counts = [], ?int $durationMs = null): self
    {
        return new self(true, $message, $counts, $durationMs);
    }

    public static function failed(string $message, ?string $error = null, array $counts = [], ?int $durationMs = null): self
    {
        return new self(false, $message, $counts, $durationMs, $error ?? $message);
    }

    public function totalRows(): int
    {
        return collect($this->counts)->sum(fn ($value) => is_numeric($value) ? (int) $value : 0);
    }

    public function toArray(): array
    {
        return [
            'ok' => $this->ok,
            'message' => $this->message,
            'counts' => $this->counts,
            'duration_ms' => $this->durationMs,
            'error' => $this->error,
            'total_rows' => $this->totalRows(),
        ];
    }
}
