<?php

declare(strict_types=1);

require __DIR__ . '/../../vendor/autoload.php';

use App\Framework\ErrorAggregation\ErrorEvent;
use App\Framework\DateTime\Clock;
use App\Framework\Core\ValueObjects\Timestamp;
use App\Framework\Exception\Core\DatabaseErrorCode;
use App\Framework\Exception\FrameworkException;
use App\Framework\Exception\ExceptionContext;
use App\Framework\Exception\RequestContext;
use App\Framework\Exception\SystemContext;
use App\Framework\Exception\ErrorHandlerContext;

// Create test clock
$clock = new class implements Clock {
    public function now(): \DateTimeImmutable { return new \DateTimeImmutable(); }
    public function fromTimestamp(Timestamp $timestamp): \DateTimeImmutable { return $timestamp->toDateTime(); }
    public function fromString(string $dateTime, ?string $format = null): \DateTimeImmutable { return new \DateTimeImmutable($dateTime); }
    public function today(): \DateTimeImmutable { return new \DateTimeImmutable('today'); }
    public function yesterday(): \DateTimeImmutable { return new \DateTimeImmutable('yesterday'); }
    public function tomorrow(): \DateTimeImmutable { return new \DateTimeImmutable('tomorrow'); }
    public function time(): Timestamp { return Timestamp::now(); }
};

echo "Creating exception and context...\n";
$exception = FrameworkException::create(
    DatabaseErrorCode::QUERY_FAILED,
    'Test database query failed'
);

$exceptionContext = ExceptionContext::empty()
    ->withOperation('test_operation', 'TestComponent')
    ->withData(['test_key' => 'test_value']);

$requestContext = RequestContext::fromGlobals();
$systemContext = SystemContext::current();

$errorHandlerContext = ErrorHandlerContext::create(
    $exceptionContext,
    $requestContext,
    $systemContext,
    ['http_status' => 500]
);

echo "Creating ErrorEvent directly...\n";
try {
    $errorEvent = ErrorEvent::fromErrorHandlerContext($errorHandlerContext, $clock);
    echo "SUCCESS: ErrorEvent created\n";
    echo "  ID: " . $errorEvent->id->toString() . "\n";
    echo "  Service: " . $errorEvent->service . "\n";
    echo "  Component: " . $errorEvent->component . "\n";
    echo "  Operation: " . $errorEvent->operation . "\n";
    echo "  Error Message: " . $errorEvent->errorMessage . "\n";
} catch (\Throwable $e) {
    echo "ERROR creating ErrorEvent: " . $e->getMessage() . "\n";
    echo "Exception class: " . get_class($e) . "\n";
    echo "Stack trace:\n" . $e->getTraceAsString() . "\n";
}
