using IWS5.Autotest.IWS5.Api.Common.Pashn.Autotests.Pashn.Api.Common;
using IWS5.Autotest.IWS5.Helpers;
using Newtonsoft.Json.Linq;
using RestSharp;
using IWS5.Autotest.IWS5.Api.ApiEndpointFormats;
using IWS5.Core.DTO;
using IWS5.Core.Models.Request;
using IWS5.Autotest.IWS5.Api.Api;

namespace IWS5.Autotest.IWS5.Api.Common
{
    public class SessionApi : BaseAppApi
    {
        private readonly AuthenticationControllerApi _authenticationControllerApi;

        public SessionStorage SessionStorage { get; } = new SessionStorage();
        public SessionApi()
            : base(ApiEndpointFormat.Authentication.Login)
        {
            _authenticationControllerApi = new AuthenticationControllerApi();
        }

        public async Task<RestResponse<LogInResponseDto>> SignIn() =>
            await SignIn(CredentialHelper.UserName, CredentialHelper.UserPassword);

        public async Task<RestResponse<LogInResponseDto>> SignIn(string username, string password, bool saveToken = true)
        {
            var response = await SendSignInRequest(username, password);

            var token = JObject.Parse(response.Content).GetValue("token")?.Value<string>();
            var userName = JObject.Parse(response.Content).GetValue("userName")?.Value<string>();
            var refreshToken = JObject.Parse(response.Content).GetValue("refreshToken")?.Value<string>();

            if (saveToken)
            {
                SessionStorage.token = token;
                SessionStorage.userName = userName;
                SessionStorage.refreshToken = refreshToken;
            }


            if (token is not null)
                return response;

            var error = JObject.Parse(response.Content).GetValue("error_description")?.Value<string>()
                        ?? throw new InvalidOperationException($"Sign in failed with status code {response.StatusCode} {response.Content} {response.ErrorMessage}");

            throw new InvalidOperationException($"Sign in failed with status code {response.StatusCode}, {error}");
        }

        public async Task<RestResponse<LogInResponseDto>> SendSignInRequest(string username, string password)
        {
            return await _authenticationControllerApi.LoginUser(
                new LogInCredentials
                {
                    UserName = CredentialHelper.UserName,
                    Password = CredentialHelper.UserPassword
                }); ;
        }


        public class SignInDto
        {
            public string Email { get; set; }
            public string Password { get; set; }

        }

        /// <summary>
        /// Wrong token generator
        /// </summary>
        public string GetWrongBearerToken()
        {
            return JwtTokenHelper.GenerateFakeJwtToken();
        }
    }
}