<?php

namespace App\Services;

use App\Models\RPublication;

/**
 * Service: PublicationSearchService
 *
 * Implements full-text search with MySQL FULLTEXT indexes for research publications.
 * Provides relevance scoring and result ranking.
 *
 * @author SSHIA Development Team
 * @version 1.0.0
 */
class PublicationSearchService
{
    /**
     * Search publications with full-text search.
     */
    public function searchPublications(string $query, array $filters = [])
    {
        $searchQuery = RPublication::published()
                                  ->with(['user', 'files']);

        // Full-text search (MySQL)
        if (config('database.default') === 'mysql' && !empty($query)) {
            $searchQuery->selectRaw(
                '*, MATCH(title, abstract, methodology, findings) AGAINST(? IN BOOLEAN MODE) as relevance',
                [$query . '*']
            )->whereRaw(
                'MATCH(title, abstract, methodology, findings) AGAINST(? IN BOOLEAN MODE)',
                [$query . '*']
            )->orderByDesc('relevance');
        } else {
            // Fallback for SQLite
            if (!empty($query)) {
                $searchQuery->where(function ($q) use ($query) {
                    $q->where('title', 'LIKE', "%{$query}%")
                      ->orWhere('abstract', 'LIKE', "%{$query}%")
                      ->orWhere('methodology', 'LIKE', "%{$query}%")
                      ->orWhere('findings', 'LIKE', "%{$query}%");
                });
            }
        }

        // Apply filters
        if (!empty($filters['category'])) {
            $searchQuery->where('category', $filters['category']);
        }

        if (!empty($filters['author_id'])) {
            $searchQuery->where('user_id', $filters['author_id']);
        }

        if (!empty($filters['from_date'])) {
            $searchQuery->whereDate('approved_at', '>=', $filters['from_date']);
        }

        if (!empty($filters['to_date'])) {
            $searchQuery->whereDate('approved_at', '<=', $filters['to_date']);
        }

        if (!empty($filters['is_featured'])) {
            $searchQuery->featured();
        }

        return $searchQuery->paginate($filters['per_page'] ?? 15);
    }

    /**
     * Get search suggestions (autocomplete).
     */
    public function getSuggestions(string $query, int $limit = 10): array
    {
        if (strlen($query) < 2) {
            return [];
        }

        return RPublication::published()
                          ->where('title', 'LIKE', "{$query}%")
                          ->limit($limit)
                          ->pluck('title')
                          ->toArray();
    }

    /**
     * Get popular search terms (from search logs).
     */
    public function getPopularSearchTerms(int $limit = 10): array
    {
        return [];
    }

    /**
     * Get search filters options.
     */
    public function getFilterOptions(): array
    {
        return [
            'categories' => [
                'clinical' => 'Clinical Research',
                'tech' => 'Technology & Innovation',
                'social' => 'Social Sciences',
            ],
            'sort_options' => [
                'relevance' => 'Relevance',
                'newest' => 'Newest First',
                'oldest' => 'Oldest First',
                'title_asc' => 'Title (A-Z)',
                'title_desc' => 'Title (Z-A)',
            ],
        ];
    }

    /**
     * Build search query with boolean operators.
     */
    public function buildBooleanQuery(string $query): string
    {
        $query = preg_replace('/[^\w\s\-]/', '', $query);

        $terms = explode(' ', $query);
        $terms = array_map(function ($term) {
            if (strlen($term) >= 3) {
                return $term . '*';
            }
            return $term;
        }, $terms);

        return implode(' ', $terms);
    }

    /**
     * Get related publications.
     */
    public function getRelatedPublications(RPublication $publication, int $limit = 5)
    {
        return RPublication::published()
                          ->where('id', '!=', $publication->id)
                          ->where('category', $publication->category)
                          ->latest('approved_at')
                          ->limit($limit)
                          ->get();
    }

    /**
     * Log search query (for analytics).
     */
    public function logSearch(string $query, int $resultsCount, ?int $userId = null): void
    {
        // Implement search logging if needed
    }

    /**
     * Get search analytics.
     */
    public function getSearchAnalytics(string $period = '30d'): array
    {
        return [
            'total_searches' => 0,
            'unique_queries' => 0,
            'avg_results_per_search' => 0,
            'zero_result_queries' => [],
            'popular_queries' => [],
        ];
    }
}
