using System.Text;
using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.MongoModels;
using adas_core.Domain.Models.Responses;
using adas_core.Domain.Utils;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using Newtonsoft.Json;

namespace adas_core.Application.Services;

public class AuthService : IAuthService
{
    private readonly IAuthorityRepository _authorityRepository;
    private readonly ILogger<AuthService> _logger;
    private readonly RecordingSettings _recordingSettings;

    //private LoginResponse? _loginResponse;

    public AuthService(IOptions<RecordingSettings> recordingSettings, ILogger<AuthService> logger,
        IAuthorityRepository authorityRepository)
    {
        _recordingSettings = recordingSettings.Value ??
                             throw new Exception("RecordingSettings must be defined on appSettings");

        _logger = logger;

        _authorityRepository = authorityRepository;

        _ = InstanceAuthUtils();
    }

    public async Task<LoginResponse?> GetLoginResponse()
    {
        try
        {
            if (_recordingSettings.RecordingApiUrl.IsEmpty())
            {
                _logger.LogInformation("Url not defined to get token on AuthUtils...");
                return null;
            }

            var user = new
            {
                Username = _recordingSettings.RecordingOrApiClientId,
                Password = _recordingSettings.RecordingOrApiClientSecret
            };

            var handler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (_, _, _, _) => true
            };

            var client = new HttpClient(handler);
            var json = JsonConvert.SerializeObject(user);

            var data = new StringContent(json, Encoding.UTF8, "application/json");
            var response = await client.PostAsync($"{_recordingSettings.RecordingApiUrl}/users/login", data);
            var respToken = response.IsSuccessStatusCode ? await response.Content.ReadAsStringAsync() : null;
            if (respToken != null)
            {
                var ton = JsonConvert.DeserializeObject<LoginResponse>(respToken);
                if (ton != null && !ton.Token.IsEmpty())
                {
                    AuthUtils.Instance.LoginResponse = ton;
                    return ton;
                }
            }

            return null;
        }
        catch (Exception e)
        {
            _logger.LogError("Error trying to get token: exception: {eMessage}", e.Message);
            return null;
        }
    }

    public async Task<string> GetToken()
    {
        var loginResponse = AuthUtils.Instance.GetLoginResponse();
        if (!loginResponse.Token.IsEmptyOrWhiteSpace() && !loginResponse.IsExpired()) return loginResponse.Token;
        var resp = await GetLoginResponse();
        if (resp != null) return resp.Token;
        _logger.LogWarning("Failed Getting token check recordingSettings for user and pass");
        return "";
    }

    public async Task<List<Authorization>> GetByUnitId(ObjectId unitId)
    {
        return await _authorityRepository.GetByUnitId(unitId);
    }

    public async Task<List<Authorization>> GetUserAuthorities(ObjectId id)
    {
        return await _authorityRepository.GetUserAuthorities(id);
    }

    public async Task<bool> DeleteByUnitId(ObjectId unitId)
    {
        return await _authorityRepository.DeleteAllAuthoritiesByUnit(unitId);
    }

    public async Task<bool> DeleteByDisplayId(ObjectId displayId)
    {
        return await _authorityRepository.DeleteAllAuthoritiesByDisplay(displayId);
    }

    private async Task InstanceAuthUtils()
    {
        if (_recordingSettings.RecordingApiUrl.IsEmpty())
        {
            _logger.LogInformation(
                "RecordingOrApiUrl not defined on appsettings RecordingSettings AuthUtils not instanciated");
            return;
        }

        if (AuthUtils.Instance.GetLoginResponse().Token.IsEmpty() || AuthUtils.Instance.GetLoginResponse().IsExpired())
        {
            _logger.LogInformation("Token is not generated or is expired sending request for new token");
            var newLoginResponse = await GetLoginResponse();
            if (newLoginResponse == null)
            {
                _logger.LogError("Token request is null check recordingSettings for user, pass and authorities");
            }
            else
            {
                _logger.LogInformation("New Token generated at UTC DATE: {DateTime} exires at: {newLoginResponse}",
                    DateTime.UtcNow, newLoginResponse.Expiration);
                AuthUtils.Instance.LoginResponse = newLoginResponse;
            }
        }
    }
}