using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using FutureMailAPI.Services;
using FutureMailAPI.DTOs;
using FutureMailAPI.Helpers;

namespace FutureMailAPI.Controllers
{
    [ApiController]
    [Route("api/v1/[controller]")]
    
    public class FileUploadController : BaseController
    {
        private readonly IFileUploadService _fileUploadService;
        private readonly ILogger<FileUploadController> _logger;
        
        public FileUploadController(IFileUploadService fileUploadService, ILogger<FileUploadController> logger)
        {
            _fileUploadService = fileUploadService;
            _logger = logger;
        }
        
        /// <summary>
        /// 上传附件
        /// </summary>
        /// <param name="request">文件上传请求</param>
        /// <returns>上传结果</returns>
        [HttpPost("attachment")]
        public async Task<IActionResult> UploadAttachment([FromForm] FileUploadWithFileRequestDto request)
        {
            try
            {
                var userId = GetCurrentUserId();
                if (userId <= 0)
                {
                    return Unauthorized(ApiResponse<object>.ErrorResult("无效的用户令牌"));
                }
                
                if (request.File == null || request.File.Length == 0)
                {
                    return BadRequest(ApiResponse<object>.ErrorResult("请选择要上传的文件"));
                }
                
                var result = await _fileUploadService.UploadFileAsync(request.File, userId, request);
                
                if (result.Success)
                {
                    return Ok(result);
                }
                
                return BadRequest(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "上传附件时发生错误");
                return StatusCode(500, ApiResponse<FileUploadResponseDto>.ErrorResult("服务器内部错误"));
            }
        }
        
        /// <summary>
        /// 上传头像
        /// </summary>
        /// <param name="request">文件上传请求</param>
        /// <returns>上传结果</returns>
        [HttpPost("avatar")]
        public async Task<IActionResult> UploadAvatar([FromForm] FileUploadWithFileRequestDto request)
        {
            try
            {
                var userId = GetCurrentUserId();
                if (userId <= 0)
                {
                    return Unauthorized(ApiResponse<object>.ErrorResult("无效的用户令牌"));
                }
                
                if (request.File == null || request.File.Length == 0)
                {
                    return BadRequest(ApiResponse<object>.ErrorResult("请选择要上传的头像文件"));
                }
                
                // 设置头像特定的属性
                request.Type = AttachmentType.IMAGE;
                request.Category = "avatar";
                
                var result = await _fileUploadService.UploadFileAsync(request.File, userId, request);
                
                if (result.Success)
                {
                    return Ok(result);
                }
                
                return BadRequest(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "上传头像时发生错误");
                return StatusCode(500, ApiResponse<FileUploadResponseDto>.ErrorResult("服务器内部错误"));
            }
        }
        
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="fileId">文件ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{fileId}")]
        public async Task<IActionResult> DeleteFile(string fileId)
        {
            try
            {
                var userId = GetCurrentUserId();
                if (userId <= 0)
                {
                    return Unauthorized(ApiResponse<object>.ErrorResult("无效的用户令牌"));
                }
                
                if (string.IsNullOrEmpty(fileId))
                {
                    return BadRequest(ApiResponse<object>.ErrorResult("文件ID不能为空"));
                }
                
                var result = await _fileUploadService.DeleteFileAsync(fileId, userId);
                
                if (result.Success)
                {
                    return Ok(result);
                }
                
                return BadRequest(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除文件时发生错误");
                return StatusCode(500, ApiResponse<bool>.ErrorResult("服务器内部错误"));
            }
        }
        
        /// <summary>
        /// 获取文件信息
        /// </summary>
        /// <param name="fileId">文件ID</param>
        /// <returns>文件信息</returns>
        [HttpGet("info/{fileId}")]
        public async Task<IActionResult> GetFile(string fileId)
        {
            try
            {
                var userId = GetCurrentUserId();
                if (userId <= 0)
                {
                    return Unauthorized(ApiResponse<object>.ErrorResult("无效的用户令牌"));
                }
                
                if (string.IsNullOrEmpty(fileId))
                {
                    return BadRequest(ApiResponse<object>.ErrorResult("文件ID不能为空"));
                }
                
                var result = await _fileUploadService.GetFileAsync(fileId, userId);
                
                if (result.Success)
                {
                    return Ok(result);
                }
                
                return BadRequest(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取文件信息时发生错误");
                return StatusCode(500, ApiResponse<FileUploadResponseDto>.ErrorResult("服务器内部错误"));
            }
        }
    }
}