using System.Data;
using IWS5.Core.Models.TriggerAction;
using Microsoft.Data.SqlClient;
using Newtonsoft.Json;

namespace PDServer.Helpers.TriggerProcessors;

public class MoveToEventTriggerProcessor : ITriggerProcessor
{
    public async Task<bool> ProcessTrigger(SqlConnection sqlConnection, string triggerAction, int workItemId)
    {
        return await ProcessTrigger(sqlConnection, triggerAction, workItemId, null);
    }

    public async Task<bool> ProcessTrigger(SqlConnection sqlConnection, string triggerAction, int workItemId, int? knownQueueId = null)
    {
        var triggerActionModel = JsonConvert.DeserializeObject<MoveToEventTriggerAction>(triggerAction);

        const string sqlStr =
            @"UPDATE ATWorkItemReference 
              SET EventID = @eventId,
                  QueueId = @queueId,
                  SourceQueueId = NULL,
                  SourceUser = NULL,
                  ServerRequest = 9, 
                  ServerRequestParam = NULL, 
                  LastActionDate = GETDATE()
              WHERE WorkItemID = @workItemId";

        using var cmd = new SqlCommand(sqlStr, sqlConnection);
        cmd.Parameters.AddWithValue("@eventId", triggerActionModel.EventId);
        cmd.Parameters.AddWithValue("@queueId", knownQueueId != null ? knownQueueId : "NULL");
        cmd.Parameters.AddWithValue("@workItemId", workItemId);

        if (sqlConnection.State != ConnectionState.Open)
            sqlConnection.Open();

        var rowsAffected = cmd.ExecuteNonQuery();
        return rowsAffected > 0;
    }
}