<?php

declare(strict_types=1);

namespace App\Domain\Sysapi\Exceptions;

use App\Domain\Sysapi\Contracts\SysapiResult;
use RuntimeException;
use Throwable;

class SysapiException extends RuntimeException
{
    public function __construct(
        string $message,
        public readonly ?SysapiResult $result = null,
        public readonly ?string $command = null,
        int $code = 0,
        ?Throwable $previous = null,
    ) {
        parent::__construct($message, $code, $previous);
    }

    public static function scriptNotFound(string $command, string $path): self
    {
        return new self(
            message: "Sysapi script bulunamadı veya çalıştırılabilir değil: {$path} (komut: {$command})",
            command: $command,
        );
    }

    public static function invalidCommand(string $command): self
    {
        return new self(
            message: "Geçersiz komut adı (whitelist regex geçmedi): {$command}",
            command: $command,
        );
    }

    public static function fromFailedResult(string $command, SysapiResult $result): self
    {
        $cat = $result->errorCategory();

        return new self(
            message: "Sysapi komutu başarısız ({$cat}, exit={$result->exitCode}): {$command} — {$result->stderr}",
            result: $result,
            command: $command,
        );
    }
}
