using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Knot.Modules.Klipy.Application.Abstractions;

namespace Knot.Modules.Klipy.Infrastructure.External;

public sealed class KlipyClient : Knot.Modules.Klipy.Application.Abstractions.IKlipyClient
{
    private readonly HttpClient _httpClient;

    public KlipyClient(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<bool> TestConnectionAsync(string apiKey, string appName, CancellationToken ct = default)
    {
        try
        {
            var url = $"https://api.klipy.com/api/v1/{apiKey}/gifs/trending?page=1&per_page=1&customer_id={appName}&locale=en";
            Console.WriteLine($"[Klipy] TestConnection URL: {url}");

            var request = new HttpRequestMessage(HttpMethod.Get, url);
            request.Headers.Add("User-Agent", "KnotMessenger/1.0");
            request.Headers.Add("Accept", "application/json");

            using var response = await _httpClient.SendAsync(request, ct);
            var responseBody = await response.Content.ReadAsStringAsync(ct);
            Console.WriteLine($"[Klipy] TestConnection response: {response.StatusCode}, body: {responseBody}");
            return response.IsSuccessStatusCode;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"[Klipy] TestConnection exception: {ex.Message}");
            return false;
        }
    }

    public async Task<List<string>> SearchVideosAsync(string apiKey, string appName, string query, int limit, CancellationToken ct = default)
    {
        return new List<string>();
    }
}
