using HoneyBox.Admin.Business.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace HoneyBox.Admin.Business.Controllers;

/// <summary>
/// 业务控制器基类
/// </summary>
[ApiController]
[Route("api/admin/business/[controller]")]
[Authorize]
public abstract class BusinessControllerBase : ControllerBase
{
    /// <summary>
    /// 返回成功响应
    /// </summary>
    protected IActionResult Ok<T>(T? data = default, string message = "success")
    {
        return base.Ok(ApiResponse<T>.Success(data, message));
    }

    /// <summary>
    /// 返回成功响应（无数据）
    /// </summary>
    protected IActionResult Ok(string message = "success")
    {
        return base.Ok(ApiResponse.Success(null, message));
    }

    /// <summary>
    /// 返回分页数据响应
    /// </summary>
    protected IActionResult Ok<T>(PagedResult<T> pagedResult, string message = "success")
    {
        return base.Ok(ApiResponse<PagedResult<T>>.Success(pagedResult, message));
    }

    /// <summary>
    /// 返回错误响应
    /// </summary>
    protected IActionResult Error(int code, string message)
    {
        return base.Ok(ApiResponse.Error(code, message));
    }

    /// <summary>
    /// 返回验证失败响应
    /// </summary>
    protected IActionResult ValidationError(string message)
    {
        return Error(BusinessErrorCodes.ValidationFailed, message);
    }

    /// <summary>
    /// 返回资源不存在响应
    /// </summary>
    protected IActionResult NotFoundError(string message = "资源不存在")
    {
        return Error(BusinessErrorCodes.NotFound, message);
    }

    /// <summary>
    /// 返回权限不足响应
    /// </summary>
    protected IActionResult PermissionDeniedError(string message = "权限不足")
    {
        return Error(BusinessErrorCodes.PermissionDenied, message);
    }

    /// <summary>
    /// 获取当前登录用户 ID
    /// </summary>
    protected long? GetCurrentUserId()
    {
        var userIdClaim = User.FindFirst("userId")?.Value;
        if (long.TryParse(userIdClaim, out var userId))
        {
            return userId;
        }
        return null;
    }

    /// <summary>
    /// 获取当前登录用户名
    /// </summary>
    protected string? GetCurrentUsername()
    {
        return User.FindFirst("username")?.Value;
    }
}
