<?php
/**
 * Search Functionality Test
 * Tests search queries and results
 */

putenv('DB_ENV=test');

require_once __DIR__ . '/../../src/Database.php';

echo "Search Functionality Test\n";
echo "=========================\n\n";

try {
    $db = Database::getInstance();

    // Test 1: Search with empty query
    echo "Test 1: Empty Search Query\n";
    $results = $db->searchTheses([]);
    if (is_array($results)) {
        echo "✓ PASS: Empty query handled (returned " . count($results) . " results)\n\n";
    } else {
        throw new Exception("Invalid results for empty query");
    }

    // Test 2: Search for specific term
    echo "Test 2: Search for Specific Term\n";
    $searchTerm = 'art'; // Common word likely to appear
    $results = $db->searchTheses(['query' => $searchTerm]);
    if (is_array($results)) {
        echo "✓ PASS: Search for '$searchTerm' returned " . count($results) . " results\n\n";
    } else {
        throw new Exception("Invalid search results");
    }

    // Test 3: Search with special characters
    echo "Test 3: Search with Special Characters\n";
    $results = $db->searchTheses(['query' => "test's \"quotes\" & symbols"]);
    if (is_array($results)) {
        echo "✓ PASS: Special characters handled safely\n\n";
    } else {
        throw new Exception("Failed to handle special characters");
    }

    // Test 4: Tag-filter search using the new EXISTS subquery
    echo "Test 4: Tag-filter search (thesis_tags subquery)\n";
    $tagResults = $db->searchTheses(['keyword' => 'urbanisme']);
    if (is_array($tagResults)) {
        echo "✓ PASS: Tag search for 'urbanisme' returned " . count($tagResults) . " result(s)\n";
        foreach ($tagResults as $r) {
            echo "  - " . $r['title'] . " (" . $r['year'] . ")\n";
        }
        echo "\n";
    } else {
        throw new Exception("Tag search returned non-array");
    }

    // Test 5: Tag search in full-text query (query touches tag subquery)
    echo "Test 5: Full-text query includes tag subquery\n";
    $allResults = $db->searchTheses(['query' => 'narration']);
    if (is_array($allResults)) {
        echo "✓ PASS: Query 'narration' returned " . count($allResults) . " result(s)\n\n";
    } else {
        throw new Exception("Full-text query with tag subquery failed");
    }

    // Test 6: countSearchResults matches searchTheses
    echo "Test 6: countSearchResults consistency\n";
    $params = ['keyword' => 'urbanisme'];
    $count  = $db->countSearchResults($params);
    $rows   = $db->searchTheses($params, 100);
    if ($count === count($rows)) {
        echo "✓ PASS: count=$count matches row count\n\n";
    } else {
        throw new Exception("countSearchResults ($count) != searchTheses row count (" . count($rows) . ")");
    }

    echo "✅ All search tests passed!\n";
    return true;

} catch (Exception $e) {
    echo "❌ FAIL: " . $e->getMessage() . "\n";
    return false;
}
