<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class ScholarService
{
    public function fetchPublications(string $url): array
    {
        try {
            // Extract Google Scholar profile ID (e.g., ssU-uBEAAAAJ)
            preg_match('/user=([^&]+)/', $url, $match);
            $profileId = $match[1] ?? null;

            if (!$profileId) {
                \Log::warning('No Google Scholar ID found in URL: ' . $url);
                return [];
            }

            // Load API key from .env
            $apiKey = env('SERPAPI_KEY');

            if (!$apiKey) {
                \Log::error('SERPAPI_KEY not found in environment variables');
                return [];
            }

            $endpoint = 'https://serpapi.com/search.json';
            $response = Http::get($endpoint, [
                'engine' => 'google_scholar_author',
                'author_id' => $profileId,
                'api_key' => $apiKey,
            ]);

            if (!$response->successful()) {
                \Log::error('Scholar API request failed: ' . $response->status());
                return [];
            }

            $json = $response->json();

            // Support multiple possible structures
            $articles = $json['articles']
                ?? $json['publications']
                ?? $json['results']
                ?? [];

            // ✅ Format and return
            return collect($articles)
                ->map(function ($a) {
                    return [
                        'title'   => $a['title'] ?? $a['name'] ?? null,
                        'authors' => $a['authors'] ?? ($a['author'] ?? null),
                        'journal' => $a['publication'] ?? $a['journal'] ?? null,
                        'year'    => $a['year'] ?? ($a['publication_year'] ?? null),
                        'link'    => $a['link'] ?? $a['citation_link'] ?? null,
                    ];
                })
                ->toArray();

        } catch (\Throwable $e) {
            \Log::error('ScholarService API error: ' . $e->getMessage());
            return [];
        }
    }
}
