using HoneyBox.Core.Interfaces;
using HoneyBox.Model.Base;
using HoneyBox.Model.Models.Announcement;
using HoneyBox.Model.Models.Config;
using HoneyBox.Model.Models.FloatBall;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace HoneyBox.Api.Controllers;

/// <summary>
/// 配置控制器 - 处理系统配置和平台配置
/// </summary>
/// <remarks>
/// 提供系统配置、商品类型、平台配置、悬浮球配置等功能
/// </remarks>
[ApiController]
[Route("api")]
public class ConfigController : ControllerBase
{
    private readonly IConfigService _configService;
    private readonly IFloatBallService _floatBallService;
    private readonly IPrizeAnnouncementService _prizeAnnouncementService;
    private readonly ILogger<ConfigController> _logger;

    public ConfigController(
        IConfigService configService,
        IFloatBallService floatBallService,
        IPrizeAnnouncementService prizeAnnouncementService,
        ILogger<ConfigController> logger)
    {
        _configService = configService;
        _floatBallService = floatBallService;
        _prizeAnnouncementService = prizeAnnouncementService;
        _logger = logger;
    }

    /// <summary>
    /// 获取系统配置
    /// </summary>
    /// <remarks>
    /// POST /api/config
    /// 
    /// 返回商品类型列表、应用设置、基础配置和版本号
    /// 支持未登录访问
    /// Requirements: 13.1
    /// </remarks>
    /// <returns>系统配置数据</returns>
    [HttpGet("config")]
    [ProducesResponseType(typeof(ApiResponse<ConfigResponseDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<ConfigResponseDto>> GetConfig()
    {
        try
        {
            var result = await _configService.GetConfigAsync();
            return ApiResponse<ConfigResponseDto>.Success(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get config");
            return ApiResponse<ConfigResponseDto>.Fail("获取配置失败");
        }
    }

    /// <summary>
    /// 获取平台配置
    /// </summary>
    /// <remarks>
    /// POST /api/getPlatformConfig
    /// 
    /// 根据请求头中的平台标识返回对应的平台配置
    /// 支持未登录访问
    /// Requirements: 13.2
    /// </remarks>
    /// <returns>平台配置数据</returns>
    [HttpGet("getPlatformConfig")]
    [ProducesResponseType(typeof(ApiResponse<PlatformConfigDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<PlatformConfigDto>> GetPlatformConfig()
    {
        try
        {
            // 从请求头获取平台标识
            var platform = Request.Headers["client"].FirstOrDefault();
            if (string.IsNullOrEmpty(platform))
            {
                platform = Request.Headers["platform"].FirstOrDefault() ?? "MP-WEIXIN";
            }

            var result = await _configService.GetPlatformConfigAsync(platform);
            return ApiResponse<PlatformConfigDto>.Success(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get platform config");
            return ApiResponse<PlatformConfigDto>.Fail("获取平台配置失败");
        }
    }

    /// <summary>
    /// 获取广告列表
    /// </summary>
    /// <remarks>
    /// GET /api/getAdvert?type_id=1
    /// 
    /// 根据广告类型获取广告列表（轮播图等）
    /// 支持未登录访问
    /// Requirements: 13.3
    /// </remarks>
    /// <param name="type_id">广告类型ID，默认为1（首页轮播图）</param>
    /// <returns>广告列表</returns>
    [HttpGet("getAdvert")]
    [HttpPost("getAdvert")]
    [ProducesResponseType(typeof(ApiResponse<List<AdvertDto>>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<List<AdvertDto>>> GetAdvert([FromQuery] int type_id = 1)
    {
        try
        {
            var result = await _configService.GetAdvertListAsync(type_id);
            return ApiResponse<List<AdvertDto>>.Success(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get advert list: TypeId={TypeId}", type_id);
            return ApiResponse<List<AdvertDto>>.Fail("获取广告列表失败");
        }
    }

    /// <summary>
    /// 获取单页内容
    /// </summary>
    /// <remarks>
    /// GET /api/getDanye?type=3
    /// 
    /// 根据类型ID获取单页内容（如用户协议、隐私政策等）
    /// 支持未登录访问
    /// </remarks>
    /// <param name="type">单页类型ID</param>
    /// <returns>单页内容数据</returns>
    [HttpGet("getDanye")]
    [ProducesResponseType(typeof(ApiResponse<DanyeDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<DanyeDto>> GetDanye([FromQuery] int type = 0)
    {
        try
        {
            var result = await _configService.GetDanyeAsync(type);
            if (result == null)
            {
                return ApiResponse<DanyeDto>.Success(new DanyeDto());
            }
            return ApiResponse<DanyeDto>.Success(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get danye: Type={Type}", type);
            return ApiResponse<DanyeDto>.Fail("获取单页内容失败");
        }
    }

    /// <summary>
    /// 获取单页内容（POST方式，带平台适配）
    /// </summary>
    /// <remarks>
    /// POST /api/danye
    /// 
    /// 根据类型ID获取单页内容，支持平台适配：
    /// - APP平台下，type 4 映射到 30，type 5 映射到 31
    /// 支持未登录访问
    /// Requirements: 14.1
    /// </remarks>
    /// <param name="request">请求参数</param>
    /// <returns>单页内容数据</returns>
    [HttpGet("danye")]
    [ProducesResponseType(typeof(ApiResponse<DanyeContentDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<DanyeContentDto>> GetDanyeContent([FromQuery] DanyeRequest? request)
    {
        try
        {
            var type = request?.Type ?? 0;
            
            // 从请求头获取平台标识
            var platform = Request.Headers["client"].FirstOrDefault();
            if (string.IsNullOrEmpty(platform))
            {
                platform = Request.Headers["platform"].FirstOrDefault();
            }

            var result = await _configService.GetDanyeContentAsync(type, platform);
            return ApiResponse<DanyeContentDto>.Success(result ?? new DanyeContentDto());
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get danye content: Type={Type}", request?.Type);
            return ApiResponse<DanyeContentDto>.Fail("获取单页内容失败");
        }
    }

    /// <summary>
    /// 获取悬浮球配置
    /// </summary>
    /// <remarks>
    /// GET /api/getFloatBall
    /// 
    /// 返回所有启用的悬浮球配置列表
    /// 支持未登录访问
    /// Requirements: 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 5.1, 5.2, 5.3
    /// </remarks>
    /// <returns>悬浮球配置列表</returns>
    [HttpGet("getFloatBall")]
    [AllowAnonymous]
    [ProducesResponseType(typeof(ApiResponse<List<FloatBallResponse>>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<List<FloatBallResponse>>> GetFloatBall()
    {
        try
        {
            var result = await _floatBallService.GetEnabledFloatBallsAsync();
            return ApiResponse<List<FloatBallResponse>>.Success(result, "获取悬浮球配置成功");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get float ball configurations");
            return ApiResponse<List<FloatBallResponse>>.Fail("获取悬浮球配置失败");
        }
    }

    /// <summary>
    /// 获取中奖公告列表
    /// </summary>
    /// <remarks>
    /// GET /api/getPrizeAnnouncements
    /// 
    /// 返回启用状态的公告列表，按排序字段升序排列
    /// 支持未登录访问
    /// Requirements: 2.1
    /// </remarks>
    /// <returns>中奖公告列表</returns>
    [HttpGet("getPrizeAnnouncements")]
    [AllowAnonymous]
    [ProducesResponseType(typeof(ApiResponse<List<PrizeAnnouncementDto>>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<List<PrizeAnnouncementDto>>> GetPrizeAnnouncements()
    {
        try
        {
            var result = await _prizeAnnouncementService.GetEnabledAnnouncementsAsync();
            return ApiResponse<List<PrizeAnnouncementDto>>.Success(result, "获取中奖公告成功");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get prize announcements");
            return ApiResponse<List<PrizeAnnouncementDto>>.Fail("获取中奖公告失败");
        }
    }
}
