<?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) {
                $msg = 'No Google Scholar ID found in URL: ' . $url;
                \Log::warning($msg);
                return ['error' => $msg];
            }

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

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

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

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

            $json = $response->json();

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

            if (empty($articles)) {
                \Log::warning('Scholar API returned no articles', ['profileId' => $profileId, 'response' => $json]);
                return ['error' => 'No publications returned by Scholar API', 'raw' => $json];
            }

            // ✅ Format and return
            $formatted = 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();

            return ['data' => $formatted];

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