using Microsoft.AspNetCore.Mvc;
using QYZH.InteractiveMagazine.IService;
using QYZH.InteractiveMagazine.Models.Common;
using QYZH.InteractiveMagazine.Models.Dto;
using QYZH.InteractiveMagazine.Models.Dto.CheckIn;

namespace QYZH.InteractiveMagazine.WebApi.Controllers.WeChat;

/// <summary>
/// 签到控制器
/// </summary>
public class CheckInController : WeChatBaseController
{
    private readonly ICheckInService _checkInService;
    private readonly ILogger<CheckInController> _logger;

    public CheckInController(ICheckInService checkInService, ILogger<CheckInController> logger)
    {
        _checkInService = checkInService;
        _logger = logger;
    }

    /// <summary>
    /// 用户签到
    /// </summary>
    /// <returns>签到结果（含奖励详情和余额）</returns>
    [HttpPost("checkIn")]
    public async Task<BaseResponse<CheckInOutput>> CheckInAsync()
    {
        try
        {
            var userId = GetCurrentUserId();
            if (userId == 0)
            {
                return BaseResponse<CheckInOutput>.Fail(ResultCode.DENY, "未获取到用户信息");
            }

            var result = await _checkInService.CheckInAsync(userId);
            return Success(result, "签到成功");
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "签到业务异常: {Message}", ex.Message);
            return BaseResponse<CheckInOutput>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "签到系统异常");
            return BaseResponse<CheckInOutput>.Fail("签到失败，请稍后重试");
        }
    }

    /// <summary>
    /// 获取签到信息（今日状态、连续天数、最近记录）
    /// </summary>
    /// <returns>签到信息</returns>
    [HttpGet("info")]
    public async Task<BaseResponse<CheckInInfoOutput>> GetCheckInInfoAsync()
    {
        try
        {
            var userId = GetCurrentUserId();
            if (userId == 0)
            {
                return BaseResponse<CheckInInfoOutput>.Fail(ResultCode.DENY, "未获取到用户信息");
            }

            var result = await _checkInService.GetCheckInInfoAsync(userId);
            return Success(result);
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "获取签到信息业务异常: {Message}", ex.Message);
            return BaseResponse<CheckInInfoOutput>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取签到信息系统异常");
            return BaseResponse<CheckInInfoOutput>.Fail("获取签到信息失败，请稍后重试");
        }
    }

    /// <summary>
    /// 补签（消耗补签卡，补签历史漏签日期）
    /// </summary>
    /// <param name="input">补签输入（目标日期）</param>
    /// <returns>补签结果（含奖励详情和余额）</returns>
    [HttpPost("makeUp")]
    public async Task<BaseResponse<CheckInOutput>> MakeUpCheckInAsync([FromBody] MakeUpCheckInInput input)
    {
        try
        {
            var userId = GetCurrentUserId();
            if (userId == 0)
            {
                return BaseResponse<CheckInOutput>.Fail(ResultCode.DENY, "未获取到用户信息");
            }

            var result = await _checkInService.MakeUpCheckInAsync(userId, input.TargetDate);
            return Success(result, "补签成功");
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "补签业务异常: {Message}", ex.Message);
            return BaseResponse<CheckInOutput>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "补签系统异常");
            return BaseResponse<CheckInOutput>.Fail("补签失败，请稍后重试");
        }
    }

    /// <summary>
    /// 获取可补签的日期列表（历史漏签日期）
    /// </summary>
    /// <param name="days">往前查看天数（默认30天）</param>
    /// <returns>漏签日期列表</returns>
    [HttpGet("missedDates")]
    public async Task<BaseResponse<List<DateTime>>> GetMissedDatesAsync([FromQuery] int days = 30)
    {
        try
        {
            var userId = GetCurrentUserId();
            if (userId == 0)
            {
                return BaseResponse<List<DateTime>>.Fail(ResultCode.DENY, "未获取到用户信息");
            }

            var result = await _checkInService.GetMissedDatesAsync(userId, days);
            return Success(result);
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "获取可补签日期业务异常: {Message}", ex.Message);
            return BaseResponse<List<DateTime>>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取可补签日期系统异常");
            return BaseResponse<List<DateTime>>.Fail("获取可补签日期失败，请稍后重试");
        }
    }
}
