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

namespace HoneyBox.Api.Controllers;

/// <summary>
/// 任务控制器 - 处理任务系统功能
/// </summary>
/// <remarks>
/// 提供任务列表查询、任务奖励领取等功能
/// </remarks>
[ApiController]
[Route("api")]
public class TaskController : ControllerBase
{
    private readonly ITaskService _taskService;
    private readonly ILogger<TaskController> _logger;

    public TaskController(
        ITaskService taskService,
        ILogger<TaskController> logger)
    {
        _taskService = taskService;
        _logger = logger;
    }

    /// <summary>
    /// 获取任务列表
    /// POST /api/task_list
    /// Requirements: 8.1-8.5
    /// </summary>
    [HttpPost("task_list")]
    [Authorize]
    public async Task<ApiResponse<TaskListResponse>> GetTaskList([FromBody] TaskListRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<TaskListResponse>.Unauthorized();
        }

        try
        {
            var type = request?.Type ?? 1;
            
            // 验证任务类型参数
            if (type != 1 && type != 2)
            {
                type = 1; // 默认为每日任务
            }

            var result = await _taskService.GetTaskListAsync(userId.Value, type);
            return ApiResponse<TaskListResponse>.Success(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get task list: UserId={UserId}", userId);
            return ApiResponse<TaskListResponse>.Fail("获取任务列表失败");
        }
    }

    /// <summary>
    /// 领取任务奖励
    /// POST /api/ling_task
    /// Requirements: 8.6-8.7
    /// </summary>
    [HttpPost("ling_task")]
    [Authorize]
    public async Task<ApiResponse<ClaimTaskRewardResponse>> ClaimTaskReward([FromBody] ClaimTaskRewardRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<ClaimTaskRewardResponse>.Unauthorized();
        }

        try
        {
            if (request == null || request.TaskListId <= 0)
            {
                return ApiResponse<ClaimTaskRewardResponse>.Fail("缺少必要参数");
            }

            var result = await _taskService.ClaimTaskRewardAsync(userId.Value, request.TaskListId);
            return ApiResponse<ClaimTaskRewardResponse>.Success(result, "领取成功");
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Claim task reward failed: UserId={UserId}, Error={Error}", userId, ex.Message);
            return ApiResponse<ClaimTaskRewardResponse>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to claim task reward: UserId={UserId}", userId);
            return ApiResponse<ClaimTaskRewardResponse>.Fail("领取任务奖励失败");
        }
    }

    #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
}
