using Common.Constant;
using Common.Logic;
using Database.Database;
using log4net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using SicboSub.Api.DTO;
using SicboSub.Api.Singleton;

namespace SicboSub.Api.Business
{
    public class UserBusinessImpl : IUserBusiness
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(UserBusinessImpl));

        private readonly ModelContext dbContext;
        private readonly IConfiguration configuration;

        public UserBusinessImpl(ModelContext _dbContext, IConfiguration _configuration)
        {
            dbContext = _dbContext;
            configuration = _configuration;
        }

        public async Task<IActionResult> GetAccountInfo(HttpRequest httpRequest, AccountInfoReq request)
        {
            var url = httpRequest.Path;
            var json = JsonConvert.SerializeObject(request);
            log.Debug("URL: " + url + " => Request: " + json);

            try
            {
                string lang = CommonLogic.GetLanguage(httpRequest, request.lang);

                string token = httpRequest.Headers["Authorization"].ToString();
                if (string.IsNullOrEmpty(token))
                {
                    return DotnetLib.Http.HttpResponse.BuildResponse(
                        log, url, json,
                        CommonErrorCode.UnauthorizedAccess,
                        ConfigManager.Instance.GetConfigWebValue("UNAUTHORIZED", lang),
                        new { }
                    );
                }
                token = token.Replace("Bearer ", "");

                if (string.IsNullOrEmpty(request.msisdn))
                {
                    return DotnetLib.Http.HttpResponse.BuildResponse(
                        log, url, json,
                        CommonErrorCode.InvalidParameter,
                        ConfigManager.Instance.GetConfigWebValue("INVALID_PARAM", lang),
                        new { }
                    );
                }

                var user = await dbContext.AccountUsers.AsNoTracking()
                    .FirstOrDefaultAsync(u => u.Msisdn == request.msisdn);

                if (user == null)
                {
                    return DotnetLib.Http.HttpResponse.BuildResponse(
                        log, url, json,
                        CommonErrorCode.UserNotFound,
                        ConfigManager.Instance.GetConfigWebValue("USER_NOT_FOUND", lang),
                        new { }
                    );
                }

                // Check active registration (Daily)
                string productCode = configuration.GetSection("PackageCodeDaily").Value;
                if (string.IsNullOrEmpty(productCode)) productCode = "SICBO_DAY";

                bool isRegistered = false;
                RegInfoDto? regPkg = null;

                var regInfo = await dbContext.RegInfos.AsNoTracking()
                    .Where(r => r.Msisdn == user.Msisdn 
                             && r.ProductName == productCode // Check config package
                             && r.Renew == 1 
                             && r.Status == 1 
                             && r.ExpireTime > DateTime.Now)
                    .OrderByDescending(r => r.RegisterTime)
                    .FirstOrDefaultAsync();

                if (regInfo != null)
                {
                    isRegistered = true;
                    regPkg = new RegInfoDto
                    {
                        RegisterId = regInfo.RegisterId,
                        Msisdn = regInfo.Msisdn,
                        ProductName = regInfo.ProductName,
                        RegisterTime = regInfo.RegisterTime,
                        NumberSpin = regInfo.NumberSpin,
                        Status = (byte)(regInfo.Status),
                        ExpireTime = regInfo.ExpireTime,
                        Renew = (byte)(regInfo.Renew ?? 0)
                    };
                }

                var result = new AccountInfoRes
                {
                    id = user.Id,
                    msisdn = user.Msisdn,
                    username = user.Username,
                    fullname = user.Fullname,
                    picture = user.Picture,
                    email = user.Email,
                    address = user.Address,
                    gender = user.Gender,
                    birthday = user.Birthday,
                    winCoin = user.WinCoin,
                    point = user.Point,
                    freeSpin = user.FreeSpin,
                    totalSpin = user.TotalSpin,
                    status = user.Status,
                    isActive = user.IsActive,
                    createdDate = user.CreatedDate,
                    lastLogin = user.LastLogin,
                    betCoin = user.BetCoin,
                    isRegistered = isRegistered,
                    regPkg = regPkg
                };

                return DotnetLib.Http.HttpResponse.BuildResponse(
                    log, url, json,
                    CommonErrorCode.Success,
                    ConfigManager.Instance.GetConfigWebValue("LOAD_SUCCESS", lang),
                    result
                );
            }
            catch (Exception ex)
            {
                log.Error("Exception: ", ex);
            }

            return DotnetLib.Http.HttpResponse.BuildResponse(
                log, url, json,
                CommonErrorCode.SystemError,
                ConfigManager.Instance.GetConfigWebValue("SYSTEM_FAILURE"),
                new { }
            );
        }
    }
}
