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

namespace FutureMailAPI.Controllers
{
    [ApiController]
    [Route("api/v1/[controller]")]
    
    public class CapsulesController : BaseController
    {
        private readonly ITimeCapsuleService _timeCapsuleService;
        private readonly ILogger<CapsulesController> _logger;
        
        public CapsulesController(ITimeCapsuleService timeCapsuleService, ILogger<CapsulesController> logger)
        {
            _timeCapsuleService = timeCapsuleService;
            _logger = logger;
        }
        
        [HttpGet]
        public async Task<IActionResult> GetCapsules()
        {
            // 从JWT令牌中获取当前用户ID
            var currentUserId = GetCurrentUserId();
            
            if (currentUserId <= 0)
            {
                return Unauthorized(ApiResponse<TimeCapsuleViewResponseDto>.ErrorResult("未授权访问"));
            }
            
            var result = await _timeCapsuleService.GetTimeCapsuleViewAsync(currentUserId);
            
            if (!result.Success)
            {
                return BadRequest(result);
            }
            
            return Ok(result);
        }
        
        [HttpPut("{capsuleId}/style")]
        public async Task<IActionResult> UpdateCapsuleStyle(int capsuleId, [FromBody] TimeCapsuleStyleUpdateDto updateDto)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ApiResponse<TimeCapsuleResponseDto>.ErrorResult("输入数据无效"));
            }
            
            // 从JWT令牌中获取当前用户ID
            var currentUserId = GetCurrentUserId();
            
            if (currentUserId <= 0)
            {
                return Unauthorized(ApiResponse<TimeCapsuleResponseDto>.ErrorResult("未授权访问"));
            }
            
            var result = await _timeCapsuleService.UpdateTimeCapsuleStyleAsync(currentUserId, capsuleId, updateDto);
            
            if (!result.Success)
            {
                return BadRequest(result);
            }
            
            return Ok(result);
        }
    }
}