<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class GifController extends Controller
{
    public function trending(Request $request)
    {
        $validated = $request->validate([
            'provider' => 'sometimes|string|in:giphy,tenor',
            'limit' => 'sometimes|integer|min:1|max:50',
            'offset' => 'sometimes|integer|min:0|max:5000',
        ]);

        $provider = $validated['provider'] ?? 'giphy';
        $limit = $validated['limit'] ?? 20;
        $offset = $validated['offset'] ?? 0;

        if ($provider === 'giphy') {
            return $this->giphyTrending($limit, $offset);
        }
        return $this->tenorTrending($limit, $offset);
    }

    public function search(Request $request)
    {
        $validated = $request->validate([
            'q' => 'required|string|min:1|max:100',
            'provider' => 'sometimes|string|in:giphy,tenor',
            'limit' => 'sometimes|integer|min:1|max:50',
            'offset' => 'sometimes|integer|min:0|max:5000',
        ]);

        $query = $validated['q'];
        $provider = $validated['provider'] ?? 'giphy';
        $limit = $validated['limit'] ?? 20;
        $offset = $validated['offset'] ?? 0;

        if ($provider === 'giphy') {
            return $this->giphySearch($query, $limit, $offset);
        }
        return $this->tenorSearch($query, $limit, $offset);
    }

    private function giphyTrending(int $limit, int $offset)
    {
        $apiKey = config('services.giphy.key') ?? env('GIPHY_API_KEY');
        if (empty($apiKey)) {
            return response()->json(['status' => 501, 'message' => 'GIPHY API key not configured'], 501);
        }
        $resp = Http::get('https://api.giphy.com/v1/gifs/trending', [
            'api_key' => $apiKey,
            'limit' => $limit,
            'offset' => $offset,
            'rating' => 'pg',
        ]);
        if (!$resp->ok()) {
            return response()->json(['status' => 502, 'message' => 'Failed to fetch trending GIFs'], 502);
        }
        $items = $this->mapGiphy($resp->json('data', []));
        return response()->json(['status' => 200, 'data' => $items]);
    }

    private function giphySearch(string $q, int $limit, int $offset)
    {
        $apiKey = config('services.giphy.key') ?? env('GIPHY_API_KEY');
        if (empty($apiKey)) {
            return response()->json(['status' => 501, 'message' => 'GIPHY API key not configured'], 501);
        }
        $resp = Http::get('https://api.giphy.com/v1/gifs/search', [
            'api_key' => $apiKey,
            'q' => $q,
            'limit' => $limit,
            'offset' => $offset,
            'rating' => 'pg',
            'lang' => 'en',
        ]);
        if (!$resp->ok()) {
            return response()->json(['status' => 502, 'message' => 'Failed to search GIFs'], 502);
        }
        $items = $this->mapGiphy($resp->json('data', []));
        return response()->json(['status' => 200, 'data' => $items]);
    }

    private function tenorTrending(int $limit, int $pos)
    {
        $apiKey = config('services.tenor.key') ?? env('TENOR_API_KEY');
        if (empty($apiKey)) {
            return response()->json(['status' => 501, 'message' => 'Tenor API key not configured'], 501);
        }
        $resp = Http::get('https://tenor.googleapis.com/v2/featured', [
            'key' => $apiKey,
            'limit' => $limit,
            'pos' => $pos,
            'media_filter' => 'minimal',
            'contentfilter' => 'high',
        ]);
        if (!$resp->ok()) {
            return response()->json(['status' => 502, 'message' => 'Failed to fetch trending GIFs'], 502);
        }
        $items = $this->mapTenor($resp->json('results', []));
        return response()->json(['status' => 200, 'data' => $items]);
    }

    private function tenorSearch(string $q, int $limit, int $pos)
    {
        $apiKey = config('services.tenor.key') ?? env('TENOR_API_KEY');
        if (empty($apiKey)) {
            return response()->json(['status' => 501, 'message' => 'Tenor API key not configured'], 501);
        }
        $resp = Http::get('https://tenor.googleapis.com/v2/search', [
            'key' => $apiKey,
            'q' => $q,
            'limit' => $limit,
            'pos' => $pos,
            'media_filter' => 'minimal',
            'contentfilter' => 'high',
        ]);
        if (!$resp->ok()) {
            return response()->json(['status' => 502, 'message' => 'Failed to search GIFs'], 502);
        }
        $items = $this->mapTenor($resp->json('results', []));
        return response()->json(['status' => 200, 'data' => $items]);
    }

    private function mapGiphy(array $data): array
    {
        return array_values(array_map(function ($item) {
            $images = $item['images'] ?? [];
            $preview = $images['fixed_width_small'] ?? $images['preview_gif'] ?? $images['downsized_small'] ?? null;
            $full = $images['original'] ?? $images['downsized'] ?? $preview;
            $previewUrl = $preview['url'] ?? $preview['mp4'] ?? null;
            $fullUrl = $full['url'] ?? null;
            return [
                'id' => $item['id'] ?? '',
                'title' => $item['title'] ?? 'GIF',
                'url' => self::httpsUrl($fullUrl),
                'preview' => self::httpsUrl($previewUrl ?? $fullUrl),
                'width' => (int)($full['width'] ?? 0),
                'height' => (int)($full['height'] ?? 0),
                'provider' => 'giphy',
            ];
        }, $data));
    }

    private function mapTenor(array $results): array
    {
        return array_values(array_map(function ($item) {
            $media = $item['media_formats'] ?? [];
            $gif = $media['gif'] ?? $media['tinygif'] ?? null;
            $previewUrl = $gif['preview'] ?? $gif['url'] ?? null;
            $fullUrl = $gif['url'] ?? $previewUrl;
            return [
                'id' => $item['id'] ?? '',
                'title' => $item['content_description'] ?? 'GIF',
                'url' => self::httpsUrl($fullUrl),
                'preview' => self::httpsUrl($previewUrl ?? $fullUrl),
                'width' => (int)($gif['dims'][0] ?? 0),
                'height' => (int)($gif['dims'][1] ?? 0),
                'provider' => 'tenor',
            ];
        }, $results));
    }

    private static function httpsUrl(?string $url): ?string
    {
        if (!$url) return null;
        return preg_replace('/^http:\\/\\//i', 'https://', $url);
    }
}


