using System.Net.Http.Json;
using Microsoft.Extensions.Configuration;

namespace AiLogia.Bot.Services;

public interface IAuthClient
{
    Task<(string token, DateTime expiresAtUtc)> CreateMagicLinkAsync(
        long tgId, string? username, string? fullName, int ttlMinutes, CancellationToken ct = default);
}

public sealed class AuthClient : IAuthClient
{
    private readonly HttpClient _http;
    private readonly string _apiKey;

    public AuthClient(HttpClient http, IConfiguration cfg)
    {
        _http = http;
        _http.BaseAddress = new Uri(cfg["AuthService:BaseUrl"]!);
        _apiKey = cfg["AuthService:ApiKey"]!;
    }

    record CreateResp(string token, DateTime expires_at_utc);

    public async Task<(string token, DateTime expiresAtUtc)> CreateMagicLinkAsync(
        long tgId, string? username, string? fullName, int ttlMinutes, CancellationToken ct = default)
    {
        var req = new
        {
            telegram_user_id = tgId,
            username,
            full_name = fullName,
            ttl_minutes = ttlMinutes
        };

        using var msg = new HttpRequestMessage(HttpMethod.Post, "/magic-links")
        {
            Content = JsonContent.Create(req)
        };
        msg.Headers.Add("X-Api-Key", _apiKey);

        using var resp = await _http.SendAsync(msg, ct); 
        resp.EnsureSuccessStatusCode();

        var data = await resp.Content.ReadFromJsonAsync<CreateResp>(cancellationToken: ct)
                   ?? throw new InvalidOperationException("Empty auth response");

        return (data.token, data.expires_at_utc);
    }
}