using HoneyBox.Admin.Business.Attributes;
using HoneyBox.Admin.Business.Models;
using HoneyBox.Admin.Business.Models.Rank;
using HoneyBox.Admin.Business.Services.Interfaces;
using Microsoft.AspNetCore.Mvc;

namespace HoneyBox.Admin.Business.Controllers;

/// <summary>
/// 排行榜管理控制器
/// </summary>
[Route("api/admin/business/[controller]")]
public class RankController : BusinessControllerBase
{
    private readonly IRankService _rankService;

    public RankController(IRankService rankService)
    {
        _rankService = rankService;
    }

    #region 周榜奖品管理

    /// <summary>
    /// 获取周榜奖品列表
    /// </summary>
    /// <param name="request">查询请求</param>
    /// <returns>分页奖品列表</returns>
    [HttpGet("week")]
    [BusinessPermission("rank:list")]
    public async Task<IActionResult> GetWeekPrizes([FromQuery] RankPrizeListRequest request)
    {
        try
        {
            var result = await _rankService.GetWeekPrizesAsync(request);
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 获取周榜奖品详情
    /// </summary>
    /// <param name="id">奖品ID</param>
    /// <returns>奖品详情</returns>
    [HttpGet("week/{id}")]
    [BusinessPermission("rank:list")]
    public async Task<IActionResult> GetWeekPrizeById(int id)
    {
        try
        {
            var result = await _rankService.GetWeekPrizeByIdAsync(id);
            if (result == null)
            {
                return NotFoundError("奖品不存在");
            }
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 创建周榜奖品
    /// </summary>
    /// <param name="request">创建请求</param>
    /// <returns>新奖品ID</returns>
    [HttpPost("week")]
    [BusinessPermission("rank:add")]
    public async Task<IActionResult> CreateWeekPrize([FromBody] RankPrizeCreateRequest request)
    {
        try
        {
            var prizeId = await _rankService.CreateWeekPrizeAsync(request);
            return Ok(new { id = prizeId }, "创建成功");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 更新周榜奖品
    /// </summary>
    /// <param name="id">奖品ID</param>
    /// <param name="request">更新请求</param>
    /// <returns>操作结果</returns>
    [HttpPut("week/{id}")]
    [BusinessPermission("rank:edit")]
    public async Task<IActionResult> UpdateWeekPrize(int id, [FromBody] RankPrizeUpdateRequest request)
    {
        try
        {
            var result = await _rankService.UpdateWeekPrizeAsync(id, request);
            return result ? Ok("更新成功") : Error(BusinessErrorCodes.InternalError, "更新失败");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 删除周榜奖品
    /// </summary>
    /// <param name="id">奖品ID</param>
    /// <returns>操作结果</returns>
    [HttpDelete("week/{id}")]
    [BusinessPermission("rank:delete")]
    public async Task<IActionResult> DeleteWeekPrize(int id)
    {
        try
        {
            var result = await _rankService.DeleteWeekPrizeAsync(id);
            return result ? Ok("删除成功") : Error(BusinessErrorCodes.InternalError, "删除失败");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 获取周榜中奖记录列表
    /// </summary>
    /// <param name="request">查询请求</param>
    /// <returns>分页中奖记录列表</returns>
    [HttpGet("week/log")]
    [BusinessPermission("rank:list")]
    public async Task<IActionResult> GetWeekLogs([FromQuery] RankLogListRequest request)
    {
        try
        {
            var result = await _rankService.GetWeekLogsAsync(request);
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
        catch (Exception ex)
        {
            // 捕获数据库表不存在等异常
            if (ex.Message.Contains("Invalid object name") || ex.InnerException?.Message.Contains("Invalid object name") == true)
            {
                return Error(BusinessErrorCodes.InternalError, "周榜记录表尚未创建，请先执行数据库迁移脚本");
            }
            throw;
        }
    }

    #endregion

    #region 月榜奖品管理

    /// <summary>
    /// 获取月榜奖品列表
    /// </summary>
    /// <param name="request">查询请求</param>
    /// <returns>分页奖品列表</returns>
    [HttpGet("month")]
    [BusinessPermission("rank:list")]
    public async Task<IActionResult> GetMonthPrizes([FromQuery] RankPrizeListRequest request)
    {
        try
        {
            var result = await _rankService.GetMonthPrizesAsync(request);
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 获取月榜奖品详情
    /// </summary>
    /// <param name="id">奖品ID</param>
    /// <returns>奖品详情</returns>
    [HttpGet("month/{id}")]
    [BusinessPermission("rank:list")]
    public async Task<IActionResult> GetMonthPrizeById(int id)
    {
        try
        {
            var result = await _rankService.GetMonthPrizeByIdAsync(id);
            if (result == null)
            {
                return NotFoundError("奖品不存在");
            }
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 创建月榜奖品
    /// </summary>
    /// <param name="request">创建请求</param>
    /// <returns>新奖品ID</returns>
    [HttpPost("month")]
    [BusinessPermission("rank:add")]
    public async Task<IActionResult> CreateMonthPrize([FromBody] RankPrizeCreateRequest request)
    {
        try
        {
            var prizeId = await _rankService.CreateMonthPrizeAsync(request);
            return Ok(new { id = prizeId }, "创建成功");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 更新月榜奖品
    /// </summary>
    /// <param name="id">奖品ID</param>
    /// <param name="request">更新请求</param>
    /// <returns>操作结果</returns>
    [HttpPut("month/{id}")]
    [BusinessPermission("rank:edit")]
    public async Task<IActionResult> UpdateMonthPrize(int id, [FromBody] RankPrizeUpdateRequest request)
    {
        try
        {
            var result = await _rankService.UpdateMonthPrizeAsync(id, request);
            return result ? Ok("更新成功") : Error(BusinessErrorCodes.InternalError, "更新失败");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 删除月榜奖品
    /// </summary>
    /// <param name="id">奖品ID</param>
    /// <returns>操作结果</returns>
    [HttpDelete("month/{id}")]
    [BusinessPermission("rank:delete")]
    public async Task<IActionResult> DeleteMonthPrize(int id)
    {
        try
        {
            var result = await _rankService.DeleteMonthPrizeAsync(id);
            return result ? Ok("删除成功") : Error(BusinessErrorCodes.InternalError, "删除失败");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 获取月榜中奖记录列表
    /// </summary>
    /// <param name="request">查询请求</param>
    /// <returns>分页中奖记录列表</returns>
    [HttpGet("month/log")]
    [BusinessPermission("rank:list")]
    public async Task<IActionResult> GetMonthLogs([FromQuery] RankLogListRequest request)
    {
        try
        {
            var result = await _rankService.GetMonthLogsAsync(request);
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
        catch (Exception ex)
        {
            // 捕获数据库表不存在等异常
            if (ex.Message.Contains("Invalid object name") || ex.InnerException?.Message.Contains("Invalid object name") == true)
            {
                return Error(BusinessErrorCodes.InternalError, "月榜记录表尚未创建，请先执行数据库迁移脚本");
            }
            throw;
        }
    }

    #endregion

    #region 用户排行榜

    /// <summary>
    /// 获取用户排行榜
    /// </summary>
    /// <param name="request">查询请求</param>
    /// <returns>分页用户排行榜</returns>
    [HttpGet("user")]
    [BusinessPermission("rank:list")]
    public async Task<IActionResult> GetUserRank([FromQuery] UserRankListRequest request)
    {
        try
        {
            var result = await _rankService.GetUserRankAsync(request);
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    #endregion

    #region 奖品类型

    /// <summary>
    /// 获取奖品类型列表
    /// </summary>
    /// <returns>奖品类型列表</returns>
    [HttpGet("prize-types")]
    [BusinessPermission("rank:list")]
    public async Task<IActionResult> GetPrizeTypes()
    {
        try
        {
            var result = await _rankService.GetPrizeTypesAsync();
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    #endregion
}
