using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Knot.Modules.Federation.Application.Abstractions;
using Knot.Shared.Kernel;
using Knot.Contracts.Settings.Application.Abstractions;
using Knot.Contracts.Settings.Application.DTOs;
using Knot.Shared.Kernel.Security;

namespace Knot.Modules.Federation.Infrastructure.Services;

/// <summary>
/// Реализация шлюза федерации с гибридным шифрованием (AES-RSA).
/// </summary>
public sealed class FederationGateway : IFederationGateway
{
    private readonly ISettingsService _settingsService;
    private readonly HttpClient _httpClient;

    public FederationGateway(ISettingsService settingsService, HttpClient httpClient)
    {
        _settingsService = settingsService;
        _httpClient = httpClient;
    }

    public async Task<Result> SendPacketAsync(FederationMessagePacket packet, string targetDomain, CancellationToken ct = default)
    {
        try
        {
            var url = $"{targetDomain.TrimEnd('/')}/api/federation/v1/inbound";
            
            // 1. Формируем тело запроса
            var content = JsonContent.Create(packet);
            
            // 2. Добавляем подпись в заголовки (как доп. уровень верификации)
            _httpClient.DefaultRequestHeaders.Remove("X-Knot-Signature");
            _httpClient.DefaultRequestHeaders.Add("X-Knot-Signature", packet.Signature);

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

            if (response.IsSuccessStatusCode)
            {
                return Result.Success();
            }

            var errorMsg = await response.Content.ReadAsStringAsync(ct);
            return Result.Failure(new Error("Federation.DeliveryFailed", $"Target server returned: {response.StatusCode}. {errorMsg}"));
        }
        catch (Exception ex)
        {
            return Result.Failure(new Error("Federation.NetworkError", ex.Message));
        }
    }
}

