using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SaasMediaWorker.Configuration;

namespace SaasMediaWorker.Services;

/// <summary>
/// NestJS Core API'ye bildirim gönderen HttpClient servisi.
/// Worker işlem tamamlandığında veya hata oluştuğunda API'yi bilgilendirir.
/// </summary>
public class ApiNotificationService
{
    private readonly HttpClient _httpClient;
    private readonly ILogger<ApiNotificationService> _logger;
    private readonly ApiSettings _settings;

    public ApiNotificationService(
        HttpClient httpClient,
        ILogger<ApiNotificationService> logger,
        IOptions<ApiSettings> settings)
    {
        _httpClient = httpClient;
        _logger = logger;
        _settings = settings.Value;

        _httpClient.BaseAddress = new Uri(_settings.CoreApiBaseUrl);
        _httpClient.Timeout = TimeSpan.FromSeconds(30);
    }

    /// <summary>
    /// Render tamamlandığında NestJS API'sine bildirim gönderir.
    /// </summary>
    public async Task NotifyCompletionAsync(
        string projectId,
        string renderJobId,
        string finalVideoUrl,
        long processingTimeMs)
    {
        var payload = new
        {
            projectId,
            renderJobId,
            status = "COMPLETED",
            finalVideoUrl,
            processingTimeMs,
            workerHostname = Environment.MachineName,
            completedAt = DateTime.UtcNow.ToString("O")
        };

        await SendNotification("/internal/worker/callback", payload);

        _logger.LogInformation(
            "✅ API'ye tamamlanma bildirimi gönderildi — Project: {ProjectId}",
            projectId);
    }

    /// <summary>
    /// Render başarısız olduğunda NestJS API'sine hata bildirimi gönderir.
    /// </summary>
    public async Task NotifyFailureAsync(
        string projectId,
        string renderJobId,
        string errorMessage,
        int attemptNumber)
    {
        var payload = new
        {
            projectId,
            renderJobId,
            status = "FAILED",
            errorMessage,
            attemptNumber,
            workerHostname = Environment.MachineName,
            failedAt = DateTime.UtcNow.ToString("O")
        };

        await SendNotification("/internal/worker/callback", payload);

        _logger.LogWarning(
            "API'ye hata bildirimi gönderildi — Project: {ProjectId}, Hata: {Error}",
            projectId, errorMessage);
    }

    private async Task SendNotification(string endpoint, object payload)
    {
        try
        {
            var content = new StringContent(
                JsonSerializer.Serialize(payload),
                Encoding.UTF8,
                "application/json");

            var response = await _httpClient.PostAsync(endpoint, content);

            if (!response.IsSuccessStatusCode)
            {
                _logger.LogWarning(
                    "API bildirim yanıtı başarısız: {StatusCode}",
                    response.StatusCode);
            }
        }
        catch (Exception ex)
        {
            // Bildirim hatası render sonucunu etkilememeli
            _logger.LogWarning(ex, "API bildirim gönderilemedi — endpoint: {Endpoint}", endpoint);
        }
    }
}
