using IWS5.Core.EventTrigger;
using IWS5.Core.Helpers;
using IWS5.Core.Models;
using IWS5.Core.Models.TriggerAction;
using IWS5.DatabaseAccess.Interfaces;
using IWS5.Services.Helpers;
using Newtonsoft.Json;

namespace IWS5.Services.EventTrigger;

public class EmailTriggerProcessor(IConnectionRepository connectionRepository, IMessageProcessor messageProcessor) : ITriggerProcessor
{
    public async Task<bool> ProcessTrigger(string triggerAction, int workItemId)
    {
        return await ProcessTrigger(triggerAction, workItemId, string.Empty, null, null, string.Empty, null);
    }
    
    public async Task<bool> ProcessTrigger(string triggerAction, int workItemId, string sourceUser = "", int? sourceQueueId = null, int? eventId = null, string lastAction = "", int? knownQueueId = null)
    {
        var mailTriggerActionData = JsonConvert.DeserializeObject<EMailTriggerAction>(triggerAction);
        var mailTask = new MailTask
        {
            Enabled = true,
            ServerId = mailTriggerActionData.ServerId,
            From = mailTriggerActionData.From,
            CC = mailTriggerActionData.CC,
            BCC = mailTriggerActionData.BCC,
            ReplyTo = mailTriggerActionData.ReplyTo,
            Subject = mailTriggerActionData.Subject,
            Recipients = mailTriggerActionData.Recipients,
            Message = mailTriggerActionData.Message,
            Priority = mailTriggerActionData.Priority
        };

        mailTask.Subject = await messageProcessor.ProcessMessage(new MessageModel {
            Message = mailTask.Subject,
            WorkItemId = workItemId,
            SourceUser = sourceUser,
            SourceQueueId = sourceQueueId.GetValueOrDefault(),
            EventId = eventId.GetValueOrDefault(),
            LastAction = lastAction,
            KnownQueueId = knownQueueId
        });
        mailTask.Message = await messageProcessor.ProcessMessage(new MessageModel
        {
            Message = mailTask.Message,
            WorkItemId = workItemId,
            SourceUser = sourceUser,
            SourceQueueId = sourceQueueId.GetValueOrDefault(),
            EventId = eventId.GetValueOrDefault(),
            LastAction = lastAction,
            KnownQueueId = knownQueueId
        });

        var connection = await connectionRepository.FindAsync(conn => conn.Id == mailTask.ServerId);
        
        if (connection == null)
            return false;

        return MailSender.SendEmail(mailTask, connection.ConnectionString, connection.UserName, connection.Password);
    }
}