SET NOCOUNT ON;
SET XACT_ABORT ON;

BEGIN TRAN;

-- Ensure new task exists
IF NOT EXISTS (
    SELECT 1
    FROM dbo.TaskExecutions WITH (UPDLOCK, HOLDLOCK)
    WHERE Id = @NewTaskId
      AND WorkspaceId = @WorkspaceId
)
    THROW 50001, 'NewTaskId does not exist in WorkspaceId.', 1;

-- If preferReleaseFromTaskId is provided and currently owns it, release it first
IF @PreferReleaseFromTaskId IS NOT NULL
    BEGIN
        UPDATE dbo.TaskExecutions
        SET ExternalSystem = NULL,
            ExternalId = NULL
        WHERE Id = @PreferReleaseFromTaskId
          AND WorkspaceId = @WorkspaceId
          AND ExternalSystem = @System
          AND ExternalId = @ExternalId;
    END

-- Lock current owner (if any) so no one else can claim concurrently
SELECT TOP 1 Id
FROM dbo.TaskExecutions WITH (UPDLOCK, HOLDLOCK)
WHERE WorkspaceId = @WorkspaceId
  AND ExternalSystem = @System
  AND ExternalId = @ExternalId;

-- Clear any remaining owner (someone else)
UPDATE dbo.TaskExecutions
SET ExternalSystem = NULL,
    ExternalId = NULL
WHERE WorkspaceId = @WorkspaceId
  AND ExternalSystem = @System
  AND ExternalId = @ExternalId
  AND Id <> @NewTaskId;

-- Assign to new task
UPDATE dbo.TaskExecutions
SET ExternalSystem = @System,
    ExternalId = @ExternalId
WHERE Id = @NewTaskId;

COMMIT;
