using Microsoft.EntityFrameworkCore;
using Quartz;
using FutureMailAPI.Data;
using FutureMailAPI.Models;

namespace FutureMailAPI.Helpers
{
    [DisallowConcurrentExecution]
    public class MailDeliveryJob : IJob
    {
        private readonly FutureMailDbContext _context;
        private readonly ILogger<MailDeliveryJob> _logger;
        
        public MailDeliveryJob(FutureMailDbContext context, ILogger<MailDeliveryJob> logger)
        {
            _context = context;
            _logger = logger;
        }
        
        public async Task Execute(IJobExecutionContext context)
        {
            _logger.LogInformation("开始执行邮件投递任务: {time}", DateTime.Now);
            
            try
            {
                // 查找所有需要投递的邮件
                var mailsToDeliver = await _context.SentMails
                    .Where(m => m.Status == 1 && m.DeliveryTime <= DateTime.UtcNow)
                    .Include(m => m.Sender)
                    .ToListAsync();
                
                _logger.LogInformation("找到 {count} 封待投递邮件", mailsToDeliver.Count);
                
                foreach (var mail in mailsToDeliver)
                {
                    try
                    {
                        // 更新邮件状态为投递中
                        mail.Status = 2;
                        await _context.SaveChangesAsync();
                        
                        // 根据收件人类型创建接收邮件记录
                        if (mail.RecipientType == 0) // 发给自己
                        {
                            var receivedMail = new ReceivedMail
                            {
                                SentMailId = mail.Id,
                                RecipientId = mail.SenderId,
                                ReceivedAt = DateTime.UtcNow
                            };
                            
                            _context.ReceivedMails.Add(receivedMail);
                        }
                        else if (mail.RecipientType == 1 && mail.RecipientId.HasValue) // 发给指定用户
                        {
                            var receivedMail = new ReceivedMail
                            {
                                SentMailId = mail.Id,
                                RecipientId = mail.RecipientId.Value,
                                ReceivedAt = DateTime.UtcNow
                            };
                            
                            _context.ReceivedMails.Add(receivedMail);
                        }
                        else if (mail.RecipientType == 2) // 公开时间胶囊
                        {
                            // 公开时间胶囊的处理逻辑，可能需要更复杂的机制
                            // 这里简化处理，暂时不实现
                        }
                        
                        // 更新邮件状态为已送达
                        mail.Status = 3;
                        
                        // 更新对应的时间胶囊状态
                        var timeCapsule = await _context.TimeCapsules
                            .FirstOrDefaultAsync(tc => tc.SentMailId == mail.Id);
                            
                        if (timeCapsule != null)
                        {
                            timeCapsule.Status = 3; // 已开启
                        }
                        
                        await _context.SaveChangesAsync();
                        
                        _logger.LogInformation("邮件 {mailId} 投递成功", mail.Id);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "投递邮件 {mailId} 时发生错误", mail.Id);
                        // 可以添加重试逻辑或错误通知
                    }
                }
                
                _logger.LogInformation("邮件投递任务完成: {time}", DateTime.Now);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "执行邮件投递任务时发生错误");
            }
        }
    }
}