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

namespace PDServer.Helpers.TriggerProcessors;

public class MoveToProcessTriggerProcessor : ITriggerProcessor
{
    public async Task<bool> ProcessTrigger(SqlConnection sqlConnection, string triggerAction, int workItemId)
    {
        var triggerActionModel = JsonConvert.DeserializeObject<MoveToProcessTriggerAction>(triggerAction);

        const string sqlStr = @"
        UPDATE ATWorkItemReference
        SET EventID = (
                SELECT TOP 1 EventID
                FROM ATEventDefinition
                WHERE ProcessID = @processId AND EventName = 'Start'
            ),
            QueueId = NULL,
            SourceQueueId = NULL,
            SourceUser = NULL,
            ServerRequest = 9,
            ServerRequestParam = NULL,
            LastActionDate = GETDATE()
        WHERE WorkItemID = @workItemId";

        using var cmd = new SqlCommand(sqlStr, sqlConnection);
        cmd.Parameters.AddWithValue("@processId", triggerActionModel.ProcessId);
        cmd.Parameters.AddWithValue("@workItemId", workItemId);

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

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