using System.Diagnostics;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.WebUtilities;
using DeviceDetectorNET;
using bitforum.Helpers;
using bitforum.Models;

namespace bitforum.Controllers.Member.Log
{
    [Authorize]
    [Route("Member/Log")]
    public class Emailontroller : Controller
    {
        private readonly ILogger<Emailontroller> _logger;
        private readonly DefaultDbContext _db;
        private string? _queryString = null;

        public Emailontroller(ILogger<Emailontroller> logger, DefaultDbContext db)
        {
            _logger = logger;
            _db = db;
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            ViewBag.QueryString = _queryString = string.Join("&", QueryHelpers.ParseQuery(HttpContext.Request.QueryString.Value).Select(r => $"{r.Key}={r.Value.FirstOrDefault()}"));

            base.OnActionExecuting(context);
        }

        [HttpGet("Email")]
        public async Task<IActionResult> Index([FromQuery] int page = 1, int perPage = 10, byte? search = null, string? keyword = null, string startAt = null!, string endAt = null!)
        {
            var query = _db.EmailChangeLog.AsQueryable();

            // 검색 조건 적용
            if (!string.IsNullOrEmpty(keyword) && search.HasValue)
            {
                if (search == 1) // ID 검색
                {
                    if (int.TryParse(keyword, out int memberID))
                    {
                        query = query.Where(log => log.MemberID == memberID);
                    }
                    else
                    {
                        query = query.Where(log => log.MemberID == 0);
                    }
                }
                else if (search == 2)
                {
                    query = query.Where(log => _db.Member.Any(c => c.Email.Contains(keyword))); // 회원 이메일 검색
                }
                else if (search == 3)
                {
                    query = query.Where(log => _db.Member.Any(c => c.Name != null && c.Name.Contains(keyword))); // 회원 별명 검색
                }
                else if (search == 4)
                {
                    query = query.Where(log => log.BeforeEmail != null && log.BeforeEmail.Contains(keyword));
                }
                else if (search == 5)
                {
                    query = query.Where(log => log.AfterEmail.Contains(keyword));
                }
            }

            var today = DateTime.UtcNow.Date;

            if (startAt != null && DateTime.TryParse(startAt, out var st))
            {
                query = query.Where(log => log.CreatedAt >= st);
            }
            if (endAt != null && DateTime.TryParse(endAt, out var et))
            {
                query = query.Where(log => log.CreatedAt <= et);
            }

            query = query.OrderByDescending(c => c.CreatedAt);


            var logs = await (from C in query
                              join M in _db.Member on C.MemberID equals M.ID into MB
                              from M in MB.DefaultIfEmpty()
                              select new
                              {
                                  M.Name,
                                  M.Email,
                                  C.ID,
                                  C.MemberID,
                                  C.BeforeEmail,
                                  C.AfterEmail,
                                  C.CreatedAt
                              }).Skip((page -1) * perPage).Take(perPage).ToListAsync();

            var data = new List<object>();
            if (logs.Count > 0)
            {
                foreach (var row in logs)
                {
                    data.Add(new
                    {
                        row.ID,
                        row.MemberID,
                        row.Name,
                        row.Email,
                        row.BeforeEmail,
                        row.AfterEmail,
                        DeleteURL = $"/Member/Log/Email/{row.ID}/Delete?{_queryString}",
                        CreatedAt = row.CreatedAt.GetDateAt()
                    });
                }
            }

            var parameter = new
            {
                Page = page,
                PerPage = perPage,
                Search = search,
                Keyword = keyword,
                StartAt = startAt,
                EndAt = endAt
            };

            ViewBag.Data = data;
            ViewBag.Total = await query.CountAsync();
            ViewBag.Parameter = parameter;
            ViewBag.Pagination = new Pagination(ViewBag.Total, page, perPage, parameter);

            return View("~/Views/Member/Log/Email.cshtml");
        }

        [HttpGet("Email/{id}/Delete")]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                if (id <= 0)
                {
                    throw new Exception("유효하지 않은 접근입니다.");
                }

                var data = await _db.NameChangeLog.FindAsync(id);
                if (data == null)
                {
                    throw new Exception("별명 변경 정보를 찾을 수 없습니다.");
                }

                _db.NameChangeLog.Remove(data);

                int affectedRows = await _db.SaveChangesAsync();
                if (affectedRows <= 0)
                {
                    throw new Exception("별명 변경 내역 삭제 중 오류가 발생했습니다.");
                }

                string message = "별명 변경 내역이 삭제되었습니다.";
                TempData["SuccessMessage"] = message;
                _logger.LogInformation(message);
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
                _logger.LogError(e, e.Message);
            }

            return Redirect($"/Member/Log/Email?{_queryString}");
        }

        [HttpPost("Email/Delete")]
        public async Task<IActionResult> Delete([FromForm] int[] ids)
        {
            try
            {
                if (ids == null || ids.Length <= 0)
                {
                    throw new Exception("유효하지 않은 접근입니다.");
                }

                foreach (var id in ids)
                {
                    var data = await _db.NameChangeLog.FindAsync(id);
                    if (data == null)
                    {
                        throw new Exception($"{id}번 이메일 변경 정보를 찾을 수 없습니다.");
                    }

                    _db.NameChangeLog.Remove(data);

                    int affectedRows = await _db.SaveChangesAsync();
                    if (affectedRows <= 0)
                    {
                        throw new Exception($"{id}번 이메일 변경 내역 삭제 중 오류가 발생했습니다.");
                    }
                }

                string message = $"{ids.Length}건의 이메일 변경 내역이 삭제되었습니다.";
                TempData["SuccessMessage"] = message;
                _logger.LogInformation(message);
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
                _logger.LogError(e, e.Message);
            }

            return Redirect($"/Member/Log/Email?{_queryString}");
        }
    }
}
