using Api;
using AutoMapper;
using Core.Db;
using Core.Repository;
using Domain.Identity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Models.Identity;
using Moq;
using Services.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Xunit.Sdk;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;

namespace Tests
{
    public class AuthTests : BaseTest
    {
        public AuthTests(WebApplicationFactory<Program> factory) : base(factory)
        {
        }

        [Fact]
        public async Task Checklogin()
        {
            await LoginWithPassword();
            var res = await _client.GetAsync("/api/Auth/CheckLogin");
            Assert.True(res.IsSuccessStatusCode);
           
        }
        [Fact]

        public async Task CreateUserAndSendOtp()
        {
            var model = new Models.Identity.OTPLoginModel { Username = "09169212241" };
            var content = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
            var res =await  _client.PostAsync("/api/Auth/Login",content);
            if (!res.IsSuccessStatusCode)
                Assert.True(false, "login was not successful");
            var otpRes= JsonConvert.DeserializeObject<OtpRequestResult>(await res.Content.ReadAsStringAsync());
            if (otpRes==null)
                Assert.True(false, "OTP result was not successful");
            Assert.True(true);

        }
        [Fact]
        public async Task LoginWithPassword()
        {
            await CreateUserAndSendOtp();
            var user = _dbContext.Accounts.FirstOrDefault(x => x.Username == "09169212241");
            var model =new Models.Identity.LoginModel { Username = "09169212241", Password = user.Password };
            var content = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
            var res =await  _client.PostAsync("/api/Auth/LoginWithPassword", content);
            if (!res.IsSuccessStatusCode)
                Assert.True(false, "login was not successful");
            var token = JsonConvert.DeserializeObject<PlainToken>(await res.Content.ReadAsStringAsync());
            if(token==null)
                Assert.True(false, "OTP result was not successful");
            _client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token.AccessToken);
            Assert.True(true);
        }
        
    }
}
