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

namespace QYZH.InteractiveMagazine.WeChatApi.Controllers;

/// <summary>
/// 小程序期刊管理控制器
/// </summary>
public class JournalController : WeChatBaseController
{
    private readonly IUserJournalService _userJournalService;
    private readonly ILogger<JournalController> _logger;

    /// <summary>
    /// 初始化小程序期刊控制器
    /// </summary>
    /// <param name="userJournalService">用户期刊关联服务</param>
    /// <param name="logger">日志服务</param>
    public JournalController(
        IUserJournalService userJournalService,
        ILogger<JournalController> logger)
    {
        _userJournalService = userJournalService;
        _logger = logger;
    }

    /// <summary>
    /// 用户扫码绑定期刊
    /// </summary>
    /// <param name="input">绑定输入（JournalId、JournalInstanceId 从扫码内容解析，Type 默认 Subscribe）</param>
    /// <returns>绑定结果</returns>
    [HttpPost("bind")]
    public async Task<BaseResponse<BindJournalOutput>> BindAsync([FromBody] BindJournalInput input)
    {
        try
        {
            var userId = GetCurrentUserId();
            if (userId == 0)
            {
                return BaseResponse<BindJournalOutput>.Fail(ResultCode.DENY, "未获取到用户信息");
            }

            var result = await _userJournalService.BindJournalAsync(userId, input);
            return Success(result, "绑定期刊成功");
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "绑定期刊业务异常: {Message}", ex.Message);
            return BaseResponse<BindJournalOutput>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "绑定期刊系统异常，参数：{Input}", input);
            return BaseResponse<BindJournalOutput>.Fail("绑定期刊失败，请稍后重试");
        }
    }

    /// <summary>
    /// 获取当前用户的期刊绑定列表
    /// </summary>
    /// <param name="input">查询条件（期刊Id、实例Id、关联类型）</param>
    /// <returns>分页结果</returns>
    [HttpPost("list")]
    public async Task<BaseResponse<PageListModel<BindJournalOutput>>> GetListAsync([FromBody] UserJournalQueryInput input)
    {
        try
        {
            var userId = GetCurrentUserId();
            if (userId == 0)
            {
                return BaseResponse<PageListModel<BindJournalOutput>>.Fail(ResultCode.DENY, "未获取到用户信息");
            }

            var result = await _userJournalService.GetUserJournalsAsync(userId, input);
            return Success(result);
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "查询期刊绑定列表业务异常: {Message}", ex.Message);
            return BaseResponse<PageListModel<BindJournalOutput>>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "查询期刊绑定列表系统异常");
            return BaseResponse<PageListModel<BindJournalOutput>>.Fail("查询期刊绑定列表失败，请稍后重试");
        }
    }
}
