using HoneyBox.Admin.Business.Attributes;
using HoneyBox.Admin.Business.Models;
using HoneyBox.Admin.Business.Models.Coupon;
using HoneyBox.Admin.Business.Services.Interfaces;
using Microsoft.AspNetCore.Mvc;

namespace HoneyBox.Admin.Business.Controllers;

/// <summary>
/// 优惠券管理控制器
/// </summary>
[Route("api/admin/business/[controller]")]
[Route("api/admin/business/coupons")] // 兼容复数形式路由
public class CouponController : BusinessControllerBase
{
    private readonly ICouponService _couponService;

    public CouponController(ICouponService couponService)
    {
        _couponService = couponService;
    }

    /// <summary>
    /// 获取优惠券模板列表（简化版，用于下拉选择）
    /// </summary>
    /// <param name="status">状态筛选：0-启用（数据库中 status=0 表示启用）</param>
    /// <returns>优惠券模板列表</returns>
    [HttpGet("templates")]
    [BusinessPermission("coupon:list")]
    public async Task<IActionResult> GetCouponTemplates([FromQuery] int? status)
    {
        try
        {
            var request = new CouponListRequest
            {
                Page = 1,
                PageSize = 100 // 获取所有优惠券
            };
            var result = await _couponService.GetCouponsAsync(request);
            // 数据库中 status=0 表示启用
            var list = status.HasValue 
                ? result.List.Where(c => c.Status == status.Value).ToList() 
                : result.List.Where(c => c.Status == 0).ToList(); // 默认返回启用的
            return Ok(list);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 获取优惠券列表
    /// </summary>
    /// <param name="request">查询请求</param>
    /// <returns>分页优惠券列表</returns>
    [HttpGet]
    [BusinessPermission("coupon:list")]
    public async Task<IActionResult> GetCoupons([FromQuery] CouponListRequest request)
    {
        try
        {
            var result = await _couponService.GetCouponsAsync(request);
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 获取优惠券详情
    /// </summary>
    /// <param name="id">优惠券ID</param>
    /// <returns>优惠券详情</returns>
    [HttpGet("{id}")]
    [BusinessPermission("coupon:list")]
    public async Task<IActionResult> GetCouponById(int id)
    {
        try
        {
            var result = await _couponService.GetCouponByIdAsync(id);
            if (result == null)
            {
                return NotFoundError("优惠券不存在");
            }
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }


    /// <summary>
    /// 创建优惠券
    /// </summary>
    /// <param name="request">创建请求</param>
    /// <returns>新优惠券ID</returns>
    [HttpPost]
    [BusinessPermission("coupon:add")]
    public async Task<IActionResult> CreateCoupon([FromBody] CouponCreateRequest request)
    {
        try
        {
            var couponId = await _couponService.CreateCouponAsync(request);
            return Ok(new { id = couponId }, "创建成功");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 更新优惠券
    /// </summary>
    /// <param name="id">优惠券ID</param>
    /// <param name="request">更新请求</param>
    /// <returns>操作结果</returns>
    [HttpPut("{id}")]
    [BusinessPermission("coupon:edit")]
    public async Task<IActionResult> UpdateCoupon(int id, [FromBody] CouponUpdateRequest request)
    {
        try
        {
            var result = await _couponService.UpdateCouponAsync(id, request);
            return result ? Ok("更新成功") : Error(BusinessErrorCodes.InternalError, "更新失败");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 删除优惠券
    /// </summary>
    /// <param name="id">优惠券ID</param>
    /// <returns>操作结果</returns>
    [HttpDelete("{id}")]
    [BusinessPermission("coupon:delete")]
    public async Task<IActionResult> DeleteCoupon(int id)
    {
        try
        {
            var result = await _couponService.DeleteCouponAsync(id);
            return result ? Ok("删除成功") : Error(BusinessErrorCodes.InternalError, "删除失败");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 修改优惠券状态
    /// </summary>
    /// <param name="id">优惠券ID</param>
    /// <param name="status">状态：0-启用 其他-禁用</param>
    /// <returns>操作结果</returns>
    [HttpPut("{id}/status")]
    [BusinessPermission("coupon:edit")]
    public async Task<IActionResult> UpdateCouponStatus(int id, [FromQuery] int status)
    {
        try
        {
            var result = await _couponService.UpdateCouponStatusAsync(id, status);
            return result ? Ok("状态更新成功") : Error(BusinessErrorCodes.InternalError, "状态更新失败");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 获取优惠券领取记录列表
    /// </summary>
    /// <param name="request">查询请求</param>
    /// <returns>分页领取记录列表</returns>
    [HttpGet("receive")]
    [BusinessPermission("coupon:list")]
    public async Task<IActionResult> GetCouponReceives([FromQuery] CouponReceiveListRequest request)
    {
        try
        {
            var result = await _couponService.GetCouponReceivesAsync(request);
            return Ok(result);
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
        catch (Exception ex)
        {
            // 捕获数据库表不存在等异常
            if (ex.Message.Contains("Invalid object name") || ex.InnerException?.Message.Contains("Invalid object name") == true)
            {
                return Error(BusinessErrorCodes.InternalError, "优惠券领取记录表尚未创建，请先执行数据库迁移脚本");
            }
            throw;
        }
    }
}
