using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using FutureMailAPI.Services;
using FutureMailAPI.DTOs;
using System.Security.Claims;

namespace FutureMailAPI.Controllers
{
    [ApiController]
    [Route("api/v1/timeline")]
    
    public class TimelineController : BaseController
    {
        private readonly IPersonalSpaceService _personalSpaceService;
        private readonly ILogger<TimelineController> _logger;
        
        public TimelineController(IPersonalSpaceService personalSpaceService, ILogger<TimelineController> logger)
        {
            _personalSpaceService = personalSpaceService;
            _logger = logger;
        }
        
        /// <summary>
        /// 获取用户时间线
        /// </summary>
        /// <param name="type">时间线类型</param>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <returns>用户时间线</returns>
        [HttpGet]
        public async Task<IActionResult> GetTimeline(
            [FromQuery] TimelineType type = TimelineType.ALL,
            [FromQuery] DateTime? startDate = null,
            [FromQuery] DateTime? endDate = null)
        {
            try
            {
                var userId = GetCurrentUserId();
                if (userId <= 0)
                {
                    return Unauthorized(ApiResponse<object>.ErrorResult("无效的用户令牌"));
                }
                
                var query = new TimelineQueryDto
                {
                    Type = type,
                    StartDate = startDate,
                    EndDate = endDate
                };
                
                var result = await _personalSpaceService.GetTimelineAsync(userId, query);
                
                if (result.Success)
                {
                    return Ok(result);
                }
                
                return BadRequest(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取时间线时发生错误");
                return StatusCode(500, ApiResponse<TimelineResponseDto>.ErrorResult("服务器内部错误"));
            }
        }
    }
}