<?php

declare(strict_types=1);

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

use App\Domain\SmartLink\Services\SmartLinkService;
use App\Domain\SmartLink\ValueObjects\{LinkType, LinkTitle, DestinationUrl, Platform};
use App\Framework\Core\AppBootstrapper;

echo "=== SmartLink Deletion Debug Test ===\n\n";

// Bootstrap application
$app = AppBootstrapper::bootstrap(__DIR__ . '/../..');
$container = $app->container;

// Get service
$service = $container->get(SmartLinkService::class);

try {
    // Create link with destinations
    echo "1. Creating SmartLink...\n";
    $link = $service->createLink(
        type: LinkType::RELEASE,
        title: LinkTitle::fromString('Test Album')
    );
    echo "   Created link: {$link->id->value}\n\n";

    // Add destinations
    echo "2. Adding destinations...\n";
    $service->addDestination(
        linkId: $link->id,
        platform: Platform::SPOTIFY,
        url: DestinationUrl::fromString('https://spotify.com/test')
    );
    $service->addDestination(
        linkId: $link->id,
        platform: Platform::APPLE_MUSIC,
        url: DestinationUrl::fromString('https://apple.com/test')
    );
    echo "   Added 2 destinations\n\n";

    // Get destinations before deletion
    echo "3. Getting destinations before deletion...\n";
    $beforeDelete = $service->getDestinations($link->id);
    echo "   Found " . count($beforeDelete) . " destinations\n\n";

    // Delete link
    echo "4. Deleting link...\n";
    $service->deleteLink($link->id);
    echo "   Link deleted\n\n";

    // Try to find deleted link
    echo "5. Trying to find deleted link (should throw exception)...\n";
    try {
        $deletedLink = $service->findById($link->id);
        echo "   ❌ ERROR: Link found when it should be deleted!\n";
    } catch (\App\Domain\SmartLink\Exceptions\SmartLinkNotFoundException $e) {
        echo "   ✅ Correctly threw SmartLinkNotFoundException: {$e->getMessage()}\n";
    } catch (\Throwable $e) {
        echo "   ❌ ERROR: Unexpected exception type: " . get_class($e) . "\n";
        echo "   Message: {$e->getMessage()}\n";
        echo "   Stack trace:\n";
        echo $e->getTraceAsString() . "\n";
    }

    echo "\n✅ Test completed\n";
} catch (\Throwable $e) {
    echo "❌ Test failed with exception:\n";
    echo "Type: " . get_class($e) . "\n";
    echo "Message: {$e->getMessage()}\n";
    echo "File: {$e->getFile()}:{$e->getLine()}\n";
    echo "\nStack trace:\n";
    echo $e->getTraceAsString() . "\n";
    exit(1);
}
