using System.Security.Claims;
using HoneyBox.Core.Interfaces;
using HoneyBox.Model.Base;
using HoneyBox.Model.Models.Sign;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace HoneyBox.Api.Controllers;

/// <summary>
/// 签到控制器 - 处理用户签到相关功能
/// </summary>
/// <remarks>
/// 提供签到信息查询、执行签到等功能
/// Requirements: 3.1-3.3
/// </remarks>
[ApiController]
[Route("api")]
public class SignController : ControllerBase
{
    private readonly ISignService _signService;
    private readonly ILogger<SignController> _logger;

    public SignController(ISignService signService, ILogger<SignController> logger)
    {
        _signService = signService;
        _logger = logger;
    }

    /// <summary>
    /// 获取签到信息
    /// </summary>
    /// <remarks>
    /// GET /api/sign_info
    /// 
    /// 返回用户签到状态、连续签到天数、签到配置等信息
    /// 未登录用户也可以查看签到配置，但不显示个人签到状态
    /// Requirements: 3.1
    /// </remarks>
    [HttpGet("sign_info")]
    [AllowAnonymous]
    [ProducesResponseType(typeof(ApiResponse<SignInfoResponse>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<SignInfoResponse>> GetSignInfo()
    {
        var userId = GetCurrentUserId();
        
        try
        {
            SignInfoResponse signInfo;
            if (userId.HasValue)
            {
                // 已登录用户，返回完整签到信息
                signInfo = await _signService.GetSignInfoAsync(userId.Value);
            }
            else
            {
                // 未登录用户，只返回签到配置
                signInfo = await _signService.GetSignConfigAsync();
            }
            return ApiResponse<SignInfoResponse>.Success(signInfo, "获取成功");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get sign info: UserId={UserId}", userId);
            return ApiResponse<SignInfoResponse>.Fail("获取签到信息失败");
        }
    }

    /// <summary>
    /// 执行签到
    /// </summary>
    /// <remarks>
    /// POST /api/sign
    /// 
    /// 执行签到操作，发放签到奖励
    /// Requirements: 3.2
    /// </remarks>
    [HttpPost("sign")]
    [Authorize]
    [ProducesResponseType(typeof(ApiResponse<SignResultResponse>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<SignResultResponse>> DoSign()
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<SignResultResponse>.Unauthorized();
        }

        try
        {
            var result = await _signService.DoSignAsync(userId.Value);
            return ApiResponse<SignResultResponse>.Success(result, "签到成功");
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Sign failed: UserId={UserId}, Error={Error}", userId, ex.Message);
            return ApiResponse<SignResultResponse>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to sign: UserId={UserId}", userId);
            return ApiResponse<SignResultResponse>.Fail("签到失败");
        }
    }

    /// <summary>
    /// 执行签到（兼容旧接口）
    /// </summary>
    /// <remarks>
    /// POST /api/sign_add
    /// 
    /// 与 /api/sign 功能相同，保持与旧版PHP接口兼容
    /// Requirements: 3.3
    /// </remarks>
    [HttpPost("sign_add")]
    [Authorize]
    [ProducesResponseType(typeof(ApiResponse<SignResultResponse>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<SignResultResponse>> SignAdd()
    {
        // 复用 DoSign 逻辑
        return await DoSign();
    }

    #region Private Helper Methods

    /// <summary>
    /// 获取当前登录用户ID
    /// </summary>
    private int? GetCurrentUserId()
    {
        var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
        if (userIdClaim == null || !int.TryParse(userIdClaim.Value, out var userId))
        {
            return null;
        }
        return userId;
    }

    #endregion
}
