using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading;
using System.Threading.Tasks;

namespace JobTrackerApi.Services.JobImport.Translation;

public sealed class LibreTranslateService : ITranslationService
{
    private readonly IHttpClientFactory _httpClientFactory;
    private readonly string _baseUrl;
    private readonly string? _apiKey;

    public LibreTranslateService(IHttpClientFactory httpClientFactory, IConfiguration cfg)
    {
        _httpClientFactory = httpClientFactory;
        _baseUrl = (cfg["Translation:LibreTranslate:BaseUrl"] ?? "").Trim().TrimEnd('/');
        _apiKey = string.IsNullOrWhiteSpace(cfg["Translation:LibreTranslate:ApiKey"]) ? null : cfg["Translation:LibreTranslate:ApiKey"]!.Trim();
    }

    public async Task<string?> TranslateToEnglishAsync(string text, string sourceLanguage, CancellationToken cancellationToken)
    {
        if (string.IsNullOrWhiteSpace(text)) return null;
        if (string.IsNullOrWhiteSpace(_baseUrl)) return null;

        using var client = _httpClientFactory.CreateClient();
        using var req = new HttpRequestMessage(HttpMethod.Post, $"{_baseUrl}/translate")
        {
            Content = JsonContent.Create(new
            {
                q = text,
                source = sourceLanguage,
                target = "en",
                format = "text",
                api_key = _apiKey
            })
        };

        using var res = await client.SendAsync(req, cancellationToken);
        if (!res.IsSuccessStatusCode) return null;

        var body = await res.Content.ReadFromJsonAsync<LibreTranslateResponse>(cancellationToken: cancellationToken);
        return string.IsNullOrWhiteSpace(body?.translatedText) ? null : body!.translatedText;
    }

    private sealed record LibreTranslateResponse(string? translatedText);
}

