using AyCode.Core.Logger;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TIAM.Database.DataLayers.Auctions;
using TIAM.Entities.Auctions;

namespace TIAMWebApp.Server.Controllers
{
    [Authorize]
    [ApiController]
    [Route("api/v1/[controller]")]
    public class AuctionAPIController : ControllerBase
    {
        private AuctionDal _auctionDal;
        private readonly IConfiguration _configuration;
        private readonly IWebHostEnvironment _webHostEnvironment;


        private readonly ILogger<UserAPIController> _logger;

        public AuctionAPIController(ILogger<UserAPIController> logger, IConfiguration configuration, IWebHostEnvironment webHostEnvironment, AuctionDal auctionDal)
        {
            _logger = logger;
            _configuration = configuration;
            _webHostEnvironment = webHostEnvironment;
            _auctionDal = auctionDal;
        }

        [AllowAnonymous]
        [HttpPost]
        [Route("CreateBid")]
        public async Task<IActionResult> CreateUser([FromBody] AuctionBid SerializedAuctionBidModel)
        {
            Logger.Info("CreateBid called");
            //if (string.IsNullOrEmpty(SerializedAuctionBidModel.GetRawText()))
            //{
            //    return BadRequest("SerializedAuctionBidModel is required");
            //}
            //else
            //{
            //AuctionBidModel? bid = JObject.Parse(SerializedAuctionBidModel.GetRawText()).ToObject<AuctionBidModel>();
            AuctionBid bid = SerializedAuctionBidModel;
            AuctionBid finalizedBidModel;

            if (bid != null)
            {
                //add userModel to users array
                //Array.Resize(ref users, users.Length + 1);
                //users[users.Length - 1] = new UserModel(user.Email, user.PhoneNumber, user.Password);

                var userId = bid.OwnerId;
                var targetProductId = bid.TargetProductId;
                string? email = bid?.Email;
                string? phoneNumber = bid?.PhoneNumber;
                int bidAmount = bid?.BidAmount ?? 0;
                bool isValid = false;

                if (userId == Guid.Empty || string.IsNullOrEmpty(email) || targetProductId == 0 || bidAmount == 0)
                {
                    return BadRequest("Invalid request");
                }
                else
                {
                    Logger.Info($"Bid to be created: {userId}, {targetProductId}, {email}, {phoneNumber}, {bidAmount}, {isValid}");
                    finalizedBidModel = new AuctionBid(userId, targetProductId, email, phoneNumber, bidAmount);
                    await _auctionDal.CreateBidAsync(finalizedBidModel);
                    return Ok(finalizedBidModel.Id);
                }
            }
            else
            {
                return BadRequest("Invalid request");
            }
            //}
        }


        [AllowAnonymous]
        [HttpGet]
        [Route("GetBids")]
        public Task<List<AuctionBid>> GetBids()
        {
            //var users = await _userDal.Ctx.Users.ToListAsync();//.GetUsersAsync();
            //return users;
            return _auctionDal.GetBids();
        }

        [AllowAnonymous]
        [HttpGet]
        [Route("GetBidsByEmail")]
        public async Task<List<AuctionBid>> GetUserByEmail(string email)
        {
            return await _auctionDal.GetBidsByEmail(email);
        }

        [AllowAnonymous]
        [HttpPost]
        [Route("ValidateBid")]
        public async Task<IActionResult> ValidateBid([FromBody] AuctionBid SerializedAuctionBidModel)
        {
            Logger.Info("ValidateBid called");
            //var validateBid = JObject.Parse(SerializedAuctionBidModel.GetRawText()).ToObject<AuctionBidModel>();

            //check if bid exists
            AuctionBid? dbBid = null;

            //Logger.Info(validateBid?.Id);
            Logger.Info(SerializedAuctionBidModel?.Id.ToString());
            //if (validateBid != null)
            if (SerializedAuctionBidModel != null)
            {
                //dbBid = await _auctionDal.GetBidById(validateBid.Id);
                dbBid = _auctionDal.GetBidById(SerializedAuctionBidModel.Id);
            }

            //check if password is valid
            //bool isValidUser = await _userManager.CheckPasswordAsync(userModel, authenticateUser.Password);

            //mocking
            if (dbBid is null)
            {
                return Unauthorized("Not found in DB");
            }
            else
            {

                //if (dbBid.Email == validateBid?.Email)
                if (dbBid.Email == SerializedAuctionBidModel?.Email)
                {
                    Logger.Info("Bid is valid");
                    dbBid.IsValid = true;
                    //Update userModel with refreshToken!!
                    await _auctionDal.UpdateBidAsync(dbBid);
                    return Ok(dbBid.IsValid);

                }
                else
                {
                    return Unauthorized("Emails not matching");
                }
            }

        }

    }
}