<?php

declare(strict_types=1);

echo "Testing PostgreSQL UUID Support\n";
echo "================================\n\n";

try {
    // Create PDO connection
    $pdo = new PDO(
        'pgsql:host=db;dbname=michaelschiemer',
        'postgres',
        'StartSimple2024!'
    );
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    echo "✅ Database connection established\n\n";

    // Create test table with UUID using raw SQL
    echo "Creating test table with UUID columns...\n";
    $pdo->exec("DROP TABLE IF EXISTS test_uuid_table");
    $pdo->exec("
        CREATE TABLE test_uuid_table (
            id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
            user_id UUID NOT NULL,
            name VARCHAR(100) NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    ");
    echo "✅ Table created successfully\n\n";

    // Insert test data
    echo "Inserting test data...\n";
    $pdo->exec("
        INSERT INTO test_uuid_table (user_id, name)
        VALUES (gen_random_uuid(), 'Test User 1')
    ");
    echo "✅ Test data inserted (UUID auto-generated)\n\n";

    // Query data
    echo "Querying data:\n";
    $stmt = $pdo->query("SELECT * FROM test_uuid_table LIMIT 1");
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    echo "  ID (auto-generated): " . $row['id'] . "\n";
    echo "  User ID: " . $row['user_id'] . "\n";
    echo "  Name: " . $row['name'] . "\n";
    echo "  Created At: " . $row['created_at'] . "\n\n";

    // Verify UUID format
    $uuidPattern = '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i';
    $isValidUuid = preg_match($uuidPattern, $row['id']);

    if ($isValidUuid) {
        echo "✅ UUID format is valid\n";
    } else {
        echo "❌ UUID format is invalid\n";
    }

    // Cleanup
    echo "\nCleaning up...\n";
    $pdo->exec("DROP TABLE IF EXISTS test_uuid_table");
    echo "✅ Test table dropped\n";

    echo "\n✅ All UUID tests passed!\n";

} catch (\Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
    echo "Stack trace:\n" . $e->getTraceAsString() . "\n";
    exit(1);
}
