using Service.EmailServices;

namespace WebApi.Controllers.EmailMessage;

[ApiController]
[Route("api/[controller]/[action]")]
public class EmailMessageController(
    IEmailMessageRepository emailRepository,
    ITransactionRecordRepository transactionRepository,
    ILogger<EmailMessageController> logger,
    IEmailHandleService emailHandleService,
    IEmailSyncService emailBackgroundService
) : ControllerBase
{
    /// <summary>
    /// 获取邮件列表（分页）
    /// </summary>
    [HttpGet]
    public async Task<PagedResponse<EmailMessageDto>> GetListAsync(
        [FromQuery] DateTime? lastReceivedDate = null,
        [FromQuery] long? lastId = null
    )
    {
        try
        {
            var (list, lastTime, lastIdResult) = await emailRepository.GetPagedListAsync(lastReceivedDate, lastId);
            var total = await emailRepository.GetTotalCountAsync();

            // 为每个邮件获取账单数量
            var emailDtos = new List<EmailMessageDto>();
            foreach (var email in list)
            {
                var transactionCount = await transactionRepository.GetCountByEmailIdAsync(email.Id);
                emailDtos.Add(EmailMessageDto.FromEntity(email, transactionCount));
            }

            return new PagedResponse<EmailMessageDto>
            {
                Success = true,
                Data = emailDtos.ToArray(),
                Total = (int)total,
                LastId = lastIdResult,
                LastTime = lastTime
            };
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "获取邮件列表失败，时间: {LastTime}, ID: {LastId}", lastReceivedDate, lastId);
            return PagedResponse<EmailMessageDto>.Fail($"获取邮件列表失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 根据ID获取邮件详情
    /// </summary>
    [HttpGet("{id}")]
    public async Task<BaseResponse<EmailMessageDto>> GetByIdAsync(long id)
    {
        try
        {
            var email = await emailRepository.GetByIdAsync(id);
            if (email == null)
            {
                return "邮件不存在".Fail<EmailMessageDto>();
            }

            // 获取账单数量
            var transactionCount = await transactionRepository.GetCountByEmailIdAsync(id);
            var emailDto = EmailMessageDto.FromEntity(email, transactionCount);

            return emailDto.Ok();
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "获取邮件详情失败，邮件ID: {EmailId}", id);
            return $"获取邮件详情失败: {ex.Message}".Fail<EmailMessageDto>();
        }
    }

    public async Task<BaseResponse> DeleteByIdAsync(long id)
    {
        try
        {
            var success = await emailRepository.DeleteAsync(id);
            if (success)
            {
                return BaseResponse.Done();
            }
            else
            {
                return "删除邮件失败，邮件不存在".Fail();
            }
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "删除邮件失败，邮件ID: {EmailId}", id);
            return $"删除邮件失败: {ex.Message}".Fail();
        }
    }

    /// <summary>
    /// 重新分析邮件并刷新交易记录
    /// </summary>
    [HttpPost]
    public async Task<BaseResponse> RefreshTransactionRecordsAsync([FromQuery] long id)
    {
        try
        {
            var email = await emailRepository.GetByIdAsync(id);
            if (email == null)
            {
                return "邮件不存在".Fail();
            }

            var success = await emailHandleService.RefreshTransactionRecordsAsync(id);
            if (success)
            {
                return BaseResponse.Done();
            }
            else
            {
                return "重新分析失败".Fail();
            }
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "重新分析邮件失败，邮件ID: {EmailId}", id);
            return $"重新分析失败: {ex.Message}".Fail();
        }
    }

    /// <summary>
    /// 立即同步邮件
    /// </summary>
    [HttpPost]
    public async Task<BaseResponse> SyncEmailsAsync()
    {
        try
        {
            await emailBackgroundService.SyncEmailsAsync();
            return "邮件同步成功".Ok();
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "同步邮件失败");
            return $"同步邮件失败: {ex.Message}".Fail();
        }
    }
}
