using System.Security.Claims;

using HoneyBox.Core.Interfaces;
using HoneyBox.Model.Base;
using HoneyBox.Model.Data;
using HoneyBox.Model.Models.Welfare;

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace HoneyBox.Api.Controllers;

/// <summary>
/// 福利屋控制器 - 处理福利屋抽奖功能
/// </summary>
/// <remarks>
/// 提供福利屋列表、详情、参与记录、中奖记录、购买等功能
/// </remarks>
[ApiController]
[Route("api")]
public class WelfareController : ControllerBase
{
    private readonly IWelfareService _welfareService;
    private readonly HoneyBoxDbContext _dbContext;
    private readonly ILogger<WelfareController> _logger;

    public WelfareController(
        IWelfareService welfareService,
        HoneyBoxDbContext dbContext,
        ILogger<WelfareController> logger)
    {
        _welfareService = welfareService;
        _dbContext = dbContext;
        _logger = logger;
    }

    /// <summary>
    /// 获取福利屋配置列表 (兼容PHP /welfare_house_list 接口)
    /// POST /api/welfare_house_list
    /// </summary>
    /// <remarks>
    /// 从 welfare_house 表获取启用的福利屋配置列表
    /// </remarks>
    [HttpPost("welfare_house_list")]
    public async Task<ApiResponse<List<WelfareHouseDto>>> GetWelfareHouseList()
    {
        try
        {
            var list = await _dbContext.WelfareHouses
                .Where(w => w.Status == 1)
                .OrderBy(w => w.Sort)
                .ThenByDescending(w => w.Id)
                .Select(w => new WelfareHouseDto
                {
                    Id = w.Id,
                    Name = w.Name,
                    Image = w.Image,
                    Url = w.Url,
                    Sort = w.Sort,
                    Status = w.Status,
                    CreateTime = w.CreateTime,
                    UpdateTime = w.UpdateTime
                })
                .ToListAsync();

            return ApiResponse<List<WelfareHouseDto>>.Success(list, "获取成功");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get welfare house list");
            return ApiResponse<List<WelfareHouseDto>>.Fail("获取福利屋列表失败");
        }
    }

    /// <summary>
    /// 获取福利屋列表 (兼容PHP /fuliwu 接口)
    /// GET/POST /api/fuliwu
    /// Requirements: 4.1
    /// </summary>
    [HttpGet("fuliwu")]
    [HttpPost("fuliwu")]
    public async Task<ApiResponse<FuliwuListResponse>> GetFuliwuList()
    {
        // 从多种来源获取参数
        var type = 1;
        var page = 1;

        // 1. 尝试从 Query 获取 (GET请求)
        if (Request.Query.ContainsKey("type"))
        {
            int.TryParse(Request.Query["type"], out type);
        }
        if (Request.Query.ContainsKey("page"))
        {
            int.TryParse(Request.Query["page"], out page);
        }

        // 2. 尝试从 Form 获取 (POST form-urlencoded)
        if (Request.HasFormContentType)
        {
            if (Request.Form.ContainsKey("type"))
            {
                int.TryParse(Request.Form["type"], out type);
            }
            if (Request.Form.ContainsKey("page"))
            {
                int.TryParse(Request.Form["page"], out page);
            }
        }
        // 3. 尝试从 JSON Body 获取 (POST application/json)
        else if (Request.ContentType?.Contains("application/json") == true)
        {
            try
            {
                Request.Body.Position = 0;
                using var reader = new StreamReader(Request.Body);
                var body = await reader.ReadToEndAsync();
                if (!string.IsNullOrEmpty(body))
                {
                    var json = System.Text.Json.JsonDocument.Parse(body);
                    if (json.RootElement.TryGetProperty("type", out var typeElement))
                    {
                        type = typeElement.GetInt32();
                    }
                    if (json.RootElement.TryGetProperty("page", out var pageElement))
                    {
                        page = pageElement.GetInt32();
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning("Failed to parse JSON body: {Error}", ex.Message);
            }
        }

        // 获取用户ID (可选，未登录用户也可以查看)
        var userId = GetCurrentUserId() ?? 0;

        try
        {
            var result = await _welfareService.GetFuliwuListAsync(userId, type, page);
            return ApiResponse<FuliwuListResponse>.Success(result);
        }
        catch (ArgumentException ex)
        {
            _logger.LogWarning("Get fuliwu list failed: UserId={UserId}, Error={Error}", userId, ex.Message);
            return ApiResponse<FuliwuListResponse>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get fuliwu list: UserId={UserId}", userId);
            return ApiResponse<FuliwuListResponse>.Fail("获取福利屋列表失败");
        }
    }

    /// <summary>
    /// 福利屋购买/参与
    /// POST /api/fuliwu_buy
    /// </summary>
    [HttpPost("fuliwu_buy")]
    [Authorize]
    public async Task<ApiResponse<WelfareBuyResponse>> BuyWelfare([FromBody] WelfareBuyRequest request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<WelfareBuyResponse>.Unauthorized();
        }

        _logger.LogInformation("BuyWelfare: UserId={UserId}, GoodsId={GoodsId}", userId, request.GoodsId);

        try
        {
            var result = await _welfareService.BuyWelfareAsync(userId.Value, request);
            return ApiResponse<WelfareBuyResponse>.Success(result, "下单成功");
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Buy welfare failed: UserId={UserId}, GoodsId={GoodsId}, Error={Error}",
                userId, request.GoodsId, ex.Message);
            return ApiResponse<WelfareBuyResponse>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to buy welfare: UserId={UserId}, GoodsId={GoodsId}",
                userId, request.GoodsId);
            return ApiResponse<WelfareBuyResponse>.Fail("购买失败,请刷新重试");
        }
    }

    /// <summary>
    /// 获取福利屋详情
    /// GET /api/fuliwu_detail
    /// Requirements: 13.1-13.4
    /// </summary>
    [HttpGet("fuliwu_detail")]
    [Authorize]
    public async Task<ApiResponse<WelfareDetailResponse>> GetWelfareDetail([FromQuery] WelfareDetailRequest? request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<WelfareDetailResponse>.Unauthorized();
        }

        // 支持从Query获取参数 (GET请求)
        var goodsId = request?.GoodsId ?? 0;
        if (Request.Query.ContainsKey("goods_id"))
        {
            int.TryParse(Request.Query["goods_id"], out goodsId);
        }

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

        try
        {
            var result = await _welfareService.GetWelfareDetailAsync(userId.Value, goodsId);
            return ApiResponse<WelfareDetailResponse>.Success(result);
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Get welfare detail failed: UserId={UserId}, GoodsId={GoodsId}, Error={Error}",
                userId, goodsId, ex.Message);
            return ApiResponse<WelfareDetailResponse>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get welfare detail: UserId={UserId}, GoodsId={GoodsId}",
                userId, goodsId);
            return ApiResponse<WelfareDetailResponse>.Fail("获取福利屋详情失败");
        }
    }


    /// <summary>
    /// 获取福利屋参与者列表
    /// GET /api/fuliwu_participants
    /// </summary>
    [HttpGet("fuliwu_participants")]
    [Authorize]
    public async Task<ApiResponse<WelfareParticipantsResponse>> GetParticipants(
        [FromQuery(Name = "goods_id")] int goodsId,
        [FromQuery] int page = 1,
        [FromQuery] int limit = 15)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<WelfareParticipantsResponse>.Unauthorized();
        }

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

        try
        {
            var result = await _welfareService.GetParticipantsAsync(goodsId, page, limit);
            return ApiResponse<WelfareParticipantsResponse>.Success(new WelfareParticipantsResponse { List = result });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get participants: GoodsId={GoodsId}", goodsId);
            return ApiResponse<WelfareParticipantsResponse>.Fail("获取参与者列表失败");
        }
    }

    /// <summary>
    /// 获取福利屋开奖记录
    /// GET /api/fuliwu_records
    /// </summary>
    [HttpGet("fuliwu_records")]
    [Authorize]
    public async Task<ApiResponse<WelfareRecordsResponse>> GetWinningRecords(
        [FromQuery(Name = "goods_id")] int goodsId,
        [FromQuery] int page = 1,
        [FromQuery] int limit = 15)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<WelfareRecordsResponse>.Unauthorized();
        }

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

        try
        {
            var result = await _welfareService.GetWinningRecordsAsync(goodsId, page, limit);
            return ApiResponse<WelfareRecordsResponse>.Success(new WelfareRecordsResponse { List = result });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get winning records: GoodsId={GoodsId}", goodsId);
            return ApiResponse<WelfareRecordsResponse>.Fail("获取开奖记录失败");
        }
    }

    /// <summary>
    /// 获取用户参与记录
    /// GET /api/fuliwu_user_records
    /// Requirements: 14.3
    /// </summary>
    [HttpGet("fuliwu_user_records")]
    [Authorize]
    public async Task<ApiResponse<List<UserParticipationDto>>> GetUserParticipationRecords(
        [FromQuery] int page = 1,
        [FromQuery] int limit = 15)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<List<UserParticipationDto>>.Unauthorized();
        }

        try
        {
            var result = await _welfareService.GetUserParticipationRecordsAsync(userId.Value, page, limit);
            return ApiResponse<List<UserParticipationDto>>.Success(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get user participation records: UserId={UserId}", userId);
            return ApiResponse<List<UserParticipationDto>>.Fail("获取用户参与记录失败");
        }
    }

    /// <summary>
    /// 获取用户中奖记录
    /// GET /api/fuliwu_user_winning_records
    /// Requirements: 14.4
    /// </summary>
    [HttpGet("fuliwu_user_winning_records")]
    [Authorize]
    public async Task<ApiResponse<List<UserWinningDto>>> GetUserWinningRecords(
        [FromQuery] int page = 1,
        [FromQuery] int limit = 15)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<List<UserWinningDto>>.Unauthorized();
        }

        try
        {
            var result = await _welfareService.GetUserWinningRecordsAsync(userId.Value, page, limit);
            return ApiResponse<List<UserWinningDto>>.Success(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get user winning records: UserId={UserId}", userId);
            return ApiResponse<List<UserWinningDto>>.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
}
