<?php

declare(strict_types=1);

use App\Framework\Database\Exception\EntityNotFoundException;
use App\Framework\Database\ValueObjects\SqlState;
use App\Framework\Exception\Core\DatabaseErrorCode;

describe('EntityNotFoundException', function () {
    it('creates exception by ID with new pattern', function () {
        $exception = EntityNotFoundException::byId('App\Domain\User', 123);

        expect($exception->getMessage())->toContain('App\Domain\User')
            ->and($exception->getMessage())->toContain('123')
            ->and($exception->getErrorCode())->toBe(DatabaseErrorCode::ENTITY_NOT_FOUND)
            ->and($exception->getContext()->data['entity_class'])->toBe('App\Domain\User')
            ->and($exception->getContext()->data['entity_id'])->toBe('123')
            ->and($exception->getContext()->data['lookup_type'])->toBe('by_id')
            ->and($exception->getCode())->toBe(404);
    });

    it('creates exception by criteria with new pattern', function () {
        $criteria = ['email' => 'test@example.com', 'status' => 'active'];
        $exception = EntityNotFoundException::byCriteria('App\Domain\User', $criteria);

        expect($exception->getMessage())->toContain('App\Domain\User')
            ->and($exception->getErrorCode())->toBe(DatabaseErrorCode::ENTITY_NOT_FOUND)
            ->and($exception->getContext()->data['entity_class'])->toBe('App\Domain\User')
            ->and($exception->getContext()->data['lookup_type'])->toBe('by_criteria')
            ->and($exception->getContext()->debug['criteria'])->toBe($criteria)
            ->and($exception->getCode())->toBe(404);
    });

    it('preserves previous exception chain', function () {
        $pdoException = new \PDOException('Row not found');
        $exception = EntityNotFoundException::byId('App\Domain\Product', 789, $pdoException);

        expect($exception->getPrevious())->toBe($pdoException);
    });

    it('is categorized as database error', function () {
        $exception = EntityNotFoundException::byId('App\Domain\Category', 1);

        expect($exception->isCategory('DB'))->toBeTrue()
            ->and($exception->getErrorCode()->getCategory())->toBe('DB');
    });

    it('is not recoverable', function () {
        $exception = EntityNotFoundException::byId('App\Domain\Tag', 1);

        expect($exception->getErrorCode()->isRecoverable())->toBeFalse();
    });

    it('has appropriate severity', function () {
        $exception = EntityNotFoundException::byId('App\Domain\Comment', 1);

        expect($exception->getErrorCode()->getSeverity()->value)->toBe('warning');
    });

    it('provides recovery hint', function () {
        $exception = EntityNotFoundException::byId('App\Domain\Post', 1);

        $hint = $exception->getErrorCode()->getRecoveryHint();
        expect($hint)->toContain('Verify entity ID');
    });
});
