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

namespace FutureMailAPI.Controllers
{
    [ApiController]
    [Route("api/v1/mails")]
    public class MailsController : BaseController
    {
        private readonly IMailService _mailService;
        private readonly ILogger<MailsController> _logger;

        public MailsController(IMailService mailService, ILogger<MailsController> logger)
        {
            _mailService = mailService;
            _logger = logger;
        }
        
        [HttpPost]
        public async Task<IActionResult> CreateMail([FromBody] SentMailCreateDto createDto)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ApiResponse<SentMailResponseDto>.ErrorResult("输入数据无效"));
            }
            
            // 从JWT令牌中获取当前用户ID
            var currentUserId = GetCurrentUserId();
            
            if (currentUserId <= 0)
            {
                return Unauthorized(ApiResponse<SentMailResponseDto>.ErrorResult("未授权访问"));
            }
            
            var result = await _mailService.CreateMailAsync(currentUserId, createDto);
            
            if (!result.Success)
            {
                return BadRequest(result);
            }
            
            return CreatedAtAction(
                nameof(GetMail), 
                new { mailId = result.Data!.Id }, 
                result);
        }
        
        // 兼容前端请求格式的创建邮件接口
        [HttpPost("create")]
        public async Task<IActionResult> CreateMailCompat([FromBody] SentMailCreateCompatDto createDto)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ApiResponse<SentMailResponseDto>.ErrorResult("输入数据无效"));
            }
            
            // 从JWT令牌中获取当前用户ID
            var currentUserId = GetCurrentUserId();
            
            if (currentUserId <= 0)
            {
                return Unauthorized(ApiResponse<SentMailResponseDto>.ErrorResult("未授权访问"));
            }
            
            // 转换为内部DTO
            var internalDto = createDto.ToInternalDto();
            
            var result = await _mailService.CreateMailAsync(currentUserId, internalDto);
            
            if (!result.Success)
            {
                return BadRequest(result);
            }
            
            return CreatedAtAction(
                nameof(GetMail), 
                new { mailId = result.Data!.Id }, 
                result);
        }
        
        [HttpGet("{mailId}")]
        public async Task<IActionResult> GetMail(int mailId)
        {
            // 从JWT令牌中获取当前用户ID
            var currentUserId = GetCurrentUserId();
            
            if (currentUserId <= 0)
            {
                return Unauthorized(ApiResponse<SentMailResponseDto>.ErrorResult("未授权访问"));
            }
            
            var result = await _mailService.GetSentMailByIdAsync(currentUserId, mailId);
            
            if (!result.Success)
            {
                return NotFound(result);
            }
            
            return Ok(result);
        }
        
        [HttpGet]
        public async Task<IActionResult> GetMails([FromQuery] MailListQueryDto queryDto)
        {
            try
            {
                // 从JWT令牌中获取当前用户ID
                var currentUserId = GetCurrentUserId();
                
                if (currentUserId <= 0)
                {
                    return Unauthorized(ApiResponse<PagedResponse<SentMailResponseDto>>.ErrorResult("未授权访问"));
                }
                
                var result = await _mailService.GetSentMailsAsync(currentUserId, queryDto);
                
                if (result.Success)
                {
                    return Ok(result);
                }
                
                return BadRequest(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取邮件列表时发生错误");
                return StatusCode(500, ApiResponse<PagedResponse<SentMailResponseDto>>.ErrorResult("服务器内部错误"));
            }
        }
        
        [HttpPut("{mailId}")]
        public async Task<IActionResult> UpdateMail(int mailId, [FromBody] SentMailUpdateDto updateDto)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ApiResponse<SentMailResponseDto>.ErrorResult("输入数据无效"));
            }
            
            // 从JWT令牌中获取当前用户ID
            var currentUserId = GetCurrentUserId();
            
            if (currentUserId <= 0)
            {
                return Unauthorized(ApiResponse<SentMailResponseDto>.ErrorResult("未授权访问"));
            }
            
            var result = await _mailService.UpdateMailAsync(currentUserId, mailId, updateDto);
            
            if (!result.Success)
            {
                return BadRequest(result);
            }
            
            return Ok(result);
        }
        
        [HttpDelete("{mailId}")]
        public async Task<IActionResult> DeleteMail(int mailId)
        {
            // 从JWT令牌中获取当前用户ID
            var currentUserId = GetCurrentUserId();
            
            if (currentUserId <= 0)
            {
                return Unauthorized(ApiResponse<bool>.ErrorResult("未授权访问"));
            }
            
            var result = await _mailService.DeleteMailAsync(currentUserId, mailId);
            
            if (!result.Success)
            {
                return BadRequest(result);
            }
            
            return Ok(result);
        }
        
        [HttpGet("received")]
        public async Task<IActionResult> GetReceivedMails([FromQuery] MailListQueryDto queryDto)
        {
            // 从JWT令牌中获取当前用户ID
            var currentUserId = GetCurrentUserId();
            
            if (currentUserId <= 0)
            {
                return Unauthorized(ApiResponse<PagedResponse<ReceivedMailResponseDto>>.ErrorResult("未授权访问"));
            }
            
            var result = await _mailService.GetReceivedMailsAsync(currentUserId, queryDto);
            
            return Ok(result);
        }
        
        [HttpGet("received/{id}")]
        public async Task<IActionResult> GetReceivedMail(int id)
        {
            // 从JWT令牌中获取当前用户ID
            var currentUserId = GetCurrentUserId();
            
            if (currentUserId <= 0)
            {
                return Unauthorized(ApiResponse<ReceivedMailResponseDto>.ErrorResult("未授权访问"));
            }
            
            var result = await _mailService.GetReceivedMailByIdAsync(currentUserId, id);
            
            if (!result.Success)
            {
                return NotFound(result);
            }
            
            return Ok(result);
        }
        
        [HttpPost("received/{id}/mark-read")]
        public async Task<IActionResult> MarkReceivedMailAsRead(int id)
        {
            // 从JWT令牌中获取当前用户ID
            var currentUserId = GetCurrentUserId();
            
            if (currentUserId <= 0)
            {
                return Unauthorized(ApiResponse<bool>.ErrorResult("未授权访问"));
            }
            
            var result = await _mailService.MarkReceivedMailAsReadAsync(currentUserId, id);
            
            if (!result.Success)
            {
                return BadRequest(result);
            }
            
            return Ok(result);
        }
        
        [HttpPost("{mailId}/revoke")]
        public async Task<IActionResult> RevokeMail(int mailId)
        {
            // 从JWT令牌中获取当前用户ID
            var currentUserId = GetCurrentUserId();
            
            if (currentUserId <= 0)
            {
                return Unauthorized(ApiResponse<bool>.ErrorResult("未授权访问"));
            }
            
            var result = await _mailService.RevokeMailAsync(currentUserId, mailId);
            
            if (!result.Success)
            {
                return BadRequest(result);
            }
            
            return Ok(result);
        }
    }
}