<?php

declare(strict_types=1);

namespace Tests\Unit\Framework\ErrorHandling\Handlers;

use App\Framework\Database\Exception\DatabaseException;
use App\Framework\ErrorHandling\Handlers\DatabaseErrorHandler;
use App\Framework\ErrorHandling\Handlers\ErrorHandlerPriority;
use App\Framework\Logging\Logger;

describe('DatabaseErrorHandler', function () {
    beforeEach(function () {
        $this->logger = $this->createMock(Logger::class);
        $this->handler = new DatabaseErrorHandler($this->logger);
    });

    it('handles DatabaseException', function () {
        $exception = DatabaseException::fromContext(
            'Connection failed',
            \App\Framework\Exception\ExceptionContext::empty()
        );

        expect($this->handler->canHandle($exception))->toBeTrue();

        $this->logger
            ->expects($this->once())
            ->method('error')
            ->with('Database error occurred', $this->anything());

        $result = $this->handler->handle($exception);

        expect($result->handled)->toBeTrue();
        expect($result->statusCode)->toBe(500);
        expect($result->data['error_type'])->toBe('database');
        expect($result->data['retry_after'])->toBe(60);
    });

    it('handles PDOException', function () {
        $exception = new \PDOException('SQLSTATE[HY000] [2002] Connection refused');

        expect($this->handler->canHandle($exception))->toBeTrue();

        $result = $this->handler->handle($exception);

        expect($result->handled)->toBeTrue();
        expect($result->statusCode)->toBe(500);
    });

    it('does not handle non-database exceptions', function () {
        $exception = new \RuntimeException('Some error');

        expect($this->handler->canHandle($exception))->toBeFalse();
    });

    it('has HIGH priority', function () {
        expect($this->handler->getPriority())->toBe(ErrorHandlerPriority::HIGH);
    });

    it('has correct name', function () {
        expect($this->handler->getName())->toBe('database_error_handler');
    });
});
