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

namespace HoneyBox.Admin.Business.Controllers;

/// <summary>
/// 文件上传控制器
/// </summary>
[Route("api/admin/upload")]
public class UploadController : BusinessControllerBase
{
    private readonly IUploadService _uploadService;

    public UploadController(IUploadService uploadService)
    {
        _uploadService = uploadService;
    }

    /// <summary>
    /// 获取预签名上传URL（客户端直传COS）
    /// </summary>
    /// <param name="request">请求参数</param>
    /// <returns>预签名URL信息，如果不支持直传则返回null</returns>
    [HttpPost("presigned-url")]
    [BusinessPermission("upload:image")]
    public async Task<IActionResult> GetPresignedUrl([FromBody] GetPresignedUrlRequest request)
    {
        try
        {
            var result = await _uploadService.GetPresignedUploadUrlAsync(request);
            if (result == null)
            {
                // 不支持直传，返回特定标识让前端走服务端上传
                return Ok(new { supportsDirectUpload = false }, "当前存储配置不支持客户端直传");
            }
            return Ok(result, "获取成功");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 上传单个图片（服务端上传，用于本地存储或降级场景）
    /// </summary>
    /// <param name="file">图片文件</param>
    /// <returns>上传结果</returns>
    [HttpPost("image")]
    [BusinessPermission("upload:image")]
    public async Task<IActionResult> UploadImage(IFormFile file)
    {
        try
        {
            var result = await _uploadService.UploadImageAsync(file);
            return Ok(result, "上传成功");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }

    /// <summary>
    /// 批量上传图片
    /// </summary>
    /// <param name="files">图片文件列表</param>
    /// <returns>上传结果列表</returns>
    [HttpPost("images")]
    [BusinessPermission("upload:image")]
    public async Task<IActionResult> UploadImages(List<IFormFile> files)
    {
        try
        {
            var results = await _uploadService.UploadImagesAsync(files);
            return Ok(results, "上传成功");
        }
        catch (BusinessException ex)
        {
            return Error(ex.Code, ex.Message);
        }
    }
}
