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

namespace HoneyBox.Api.Controllers;

/// <summary>
/// 收藏控制器 - 处理商品收藏功能
/// </summary>
/// <remarks>
/// 提供商品收藏、取消收藏、收藏列表查询等功能
/// Requirements: 6.1-6.4
/// </remarks>
[ApiController]
[Route("api")]
public class CollectionController : ControllerBase
{
    private readonly ICollectionService _collectionService;
    private readonly ILogger<CollectionController> _logger;

    public CollectionController(
        ICollectionService collectionService,
        ILogger<CollectionController> logger)
    {
        _collectionService = collectionService;
        _logger = logger;
    }

    /// <summary>
    /// 收藏/取消收藏商品
    /// POST /api/addCollect
    /// Requirements: 6.1-6.3
    /// </summary>
    /// <remarks>
    /// 切换收藏状态：如果已收藏则取消收藏，如果未收藏则添加收藏
    /// </remarks>
    [HttpPost("addCollect")]
    [Authorize]
    public async Task<ApiResponse> ToggleCollection([FromBody] CollectionRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse.Unauthorized();
        }

        try
        {
            if (request == null || request.GoodsId <= 0)
            {
                return ApiResponse.Fail("商品ID不能为空");
            }

            var result = await _collectionService.ToggleCollectionAsync(
                userId.Value, 
                request.GoodsId, 
                request.GoodsNum);

            return result 
                ? ApiResponse.Success("操作成功") 
                : ApiResponse.Fail("操作失败");
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Toggle collection failed: UserId={UserId}, GoodsId={GoodsId}, Error={Error}", 
                userId, request?.GoodsId, ex.Message);
            return ApiResponse.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to toggle collection: UserId={UserId}, GoodsId={GoodsId}", 
                userId, request?.GoodsId);
            return ApiResponse.Fail("操作失败");
        }
    }

    /// <summary>
    /// 获取收藏列表
    /// POST /api/listCollect
    /// Requirements: 6.4
    /// </summary>
    [HttpPost("listCollect")]
    [Authorize]
    public async Task<ApiResponse<CollectionListResponse>> GetCollectionList([FromBody] CollectionListRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<CollectionListResponse>.Unauthorized();
        }

        try
        {
            request ??= new CollectionListRequest();
            var page = request.Page < 1 ? 1 : request.Page;
            var pageSize = request.PageSize < 1 ? 100 : request.PageSize;

            var result = await _collectionService.GetCollectionListAsync(
                userId.Value, 
                request.Type, 
                page, 
                pageSize);

            return ApiResponse<CollectionListResponse>.Success(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get collection list: UserId={UserId}", userId);
            return ApiResponse<CollectionListResponse>.Fail("获取收藏列表失败");
        }
    }

    /// <summary>
    /// 获取收藏列表 (GET方式 - 兼容前端)
    /// GET /api/collect_list
    /// Requirements: 9.1
    /// </summary>
    [HttpGet("collect_list")]
    [Authorize]
    public async Task<ApiResponse<CollectionListResponse>> GetCollectionListGet(
        [FromQuery] int page = 1, 
        [FromQuery] int pageSize = 100,
        [FromQuery] int type = 0)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<CollectionListResponse>.Unauthorized();
        }

        try
        {
            page = page < 1 ? 1 : page;
            pageSize = pageSize < 1 ? 100 : pageSize;

            var result = await _collectionService.GetCollectionListAsync(
                userId.Value, 
                type, 
                page, 
                pageSize);

            return ApiResponse<CollectionListResponse>.Success(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get collection list: UserId={UserId}", userId);
            return ApiResponse<CollectionListResponse>.Fail("获取收藏列表失败");
        }
    }

    /// <summary>
    /// 删除收藏
    /// POST /api/delCollect
    /// </summary>
    [HttpPost("delCollect")]
    [Authorize]
    public async Task<ApiResponse> DeleteCollection([FromBody] DeleteCollectionRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse.Unauthorized();
        }

        try
        {
            if (request == null || request.Id <= 0)
            {
                return ApiResponse.Fail("收藏ID不能为空");
            }

            var result = await _collectionService.DeleteCollectionAsync(userId.Value, request.Id);

            return result 
                ? ApiResponse.Success("删除成功") 
                : ApiResponse.Fail("删除失败");
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Delete collection failed: UserId={UserId}, CollectionId={CollectionId}, Error={Error}", 
                userId, request?.Id, ex.Message);
            return ApiResponse.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to delete collection: UserId={UserId}, CollectionId={CollectionId}", 
                userId, request?.Id);
            return ApiResponse.Fail("删除失败");
        }
    }

    /// <summary>
    /// 取消收藏 (通过商品ID - 兼容前端)
    /// POST /api/cancelCollect
    /// Requirements: 9.2
    /// </summary>
    [HttpPost("cancelCollect")]
    [Authorize]
    public async Task<ApiResponse> CancelCollectionByGoodsId([FromBody] CancelCollectionRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse.Unauthorized();
        }

        try
        {
            if (request == null || request.GoodsId <= 0)
            {
                return ApiResponse.Fail("商品ID不能为空");
            }

            var result = await _collectionService.CancelCollectionByGoodsIdAsync(userId.Value, request.GoodsId);

            return result 
                ? ApiResponse.Success("取消收藏成功") 
                : ApiResponse.Fail("取消收藏失败");
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Cancel collection failed: UserId={UserId}, GoodsId={GoodsId}, Error={Error}", 
                userId, request?.GoodsId, ex.Message);
            return ApiResponse.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to cancel collection: UserId={UserId}, GoodsId={GoodsId}", 
                userId, request?.GoodsId);
            return ApiResponse.Fail("取消收藏失败");
        }
    }

    /// <summary>
    /// 查询商品收藏状态
    /// </summary>
    /// <remarks>
    /// POST /api/goods_collection_status
    /// 
    /// 查询指定商品是否已被当前用户收藏
    /// 注：此接口从商品详情接口(goods_detail)中拆分出来，使商品详情接口可以不依赖用户登录状态
    /// Requirements: 6.1
    /// </remarks>
    /// <param name="request">收藏状态请求参数，包含商品ID和箱号</param>
    /// <returns>收藏状态</returns>
    [HttpPost("goods_collection_status")]
    [Authorize]
    [ProducesResponseType(typeof(ApiResponse<CollectionStatusResponse>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<CollectionStatusResponse>), StatusCodes.Status401Unauthorized)]
    public async Task<ApiResponse<CollectionStatusResponse>> GetCollectionStatus([FromBody] CollectionStatusRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<CollectionStatusResponse>.Unauthorized();
        }

        try
        {
            if (request == null || request.GoodsId <= 0)
            {
                return ApiResponse<CollectionStatusResponse>.Fail("商品ID不能为空");
            }

            var isCollected = await _collectionService.IsCollectedAsync(
                userId.Value, 
                request.GoodsId, 
                request.GoodsNum);

            return ApiResponse<CollectionStatusResponse>.Success(new CollectionStatusResponse
            {
                CollectionIs = isCollected ? 1 : 0
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get collection status: UserId={UserId}, GoodsId={GoodsId}", 
                userId, request?.GoodsId);
            return ApiResponse<CollectionStatusResponse>.Fail("获取收藏状态失败");
        }
    }

    /// <summary>
    /// 查询商品收藏状态 (GET方式 - 兼容前端)
    /// GET /api/collect_status
    /// Requirements: 9.3
    /// </summary>
    [HttpGet("collect_status")]
    [Authorize]
    [ProducesResponseType(typeof(ApiResponse<CollectionStatusResponse>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<CollectionStatusResponse>), StatusCodes.Status401Unauthorized)]
    public async Task<ApiResponse<CollectionStatusResponse>> GetCollectionStatusGet(
        [FromQuery(Name = "goods_id")] int goodsId,
        [FromQuery(Name = "goods_num")] int goodsNum = 0)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<CollectionStatusResponse>.Unauthorized();
        }

        try
        {
            if (goodsId <= 0)
            {
                return ApiResponse<CollectionStatusResponse>.Fail("商品ID不能为空");
            }

            var isCollected = await _collectionService.IsCollectedAsync(
                userId.Value, 
                goodsId, 
                goodsNum);

            return ApiResponse<CollectionStatusResponse>.Success(new CollectionStatusResponse
            {
                CollectionIs = isCollected ? 1 : 0
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get collection status: UserId={UserId}, GoodsId={GoodsId}", 
                userId, goodsId);
            return ApiResponse<CollectionStatusResponse>.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
}
