<?php

namespace App\Services\BackupScheduling;

use App\Services\Graph\GraphException;
use Throwable;

class RunErrorMapper
{
    public const ERROR_TOKEN_EXPIRED = 'TOKEN_EXPIRED';

    public const ERROR_PERMISSION_MISSING = 'PERMISSION_MISSING';

    public const ERROR_GRAPH_THROTTLE = 'GRAPH_THROTTLE';

    public const ERROR_GRAPH_UNAVAILABLE = 'GRAPH_UNAVAILABLE';

    public const ERROR_UNKNOWN = 'UNKNOWN';

    /**
     * @return array{shouldRetry: bool, delay: int, error_code: string, error_message: string, final_status: string}
     */
    public function map(Throwable $throwable, int $attempt, int $maxAttempts = 3): array
    {
        $attempt = max(1, $attempt);

        if ($throwable instanceof GraphException) {
            $status = $throwable->status;

            if ($status === 401) {
                return $this->final(self::ERROR_TOKEN_EXPIRED, $throwable->getMessage());
            }

            if ($status === 403) {
                return $this->final(self::ERROR_PERMISSION_MISSING, $throwable->getMessage());
            }

            if ($status === 429) {
                return $this->retry(self::ERROR_GRAPH_THROTTLE, $throwable->getMessage(), $attempt, $maxAttempts);
            }

            if ($status === 503) {
                return $this->retry(self::ERROR_GRAPH_UNAVAILABLE, $throwable->getMessage(), $attempt, $maxAttempts);
            }

            return $this->retry(self::ERROR_UNKNOWN, $throwable->getMessage(), $attempt, $maxAttempts);
        }

        return $this->retry(self::ERROR_UNKNOWN, $throwable->getMessage(), $attempt, $maxAttempts);
    }

    /**
     * @return array{shouldRetry: bool, delay: int, error_code: string, error_message: string, final_status: string}
     */
    private function retry(string $code, string $message, int $attempt, int $maxAttempts): array
    {
        if ($attempt >= $maxAttempts) {
            return $this->final($code, $message);
        }

        $delays = [60, 300, 900];
        $delay = $delays[min($attempt - 1, count($delays) - 1)];

        return [
            'shouldRetry' => true,
            'delay' => $delay,
            'error_code' => $code,
            'error_message' => $message,
            'final_status' => 'failed',
        ];
    }

    /**
     * @return array{shouldRetry: bool, delay: int, error_code: string, error_message: string, final_status: string}
     */
    private function final(string $code, string $message): array
    {
        return [
            'shouldRetry' => false,
            'delay' => 0,
            'error_code' => $code,
            'error_message' => $message,
            'final_status' => 'failed',
        ];
    }
}
