{% macro insert_A_MOPDB_LOAD_HISTORY() %}
{% if execute %}

    {% set insert_A_MOPDB_LOAD_HISTORY %}
        INSERT INTO {{ source('control_tables', 'A_MOPDB_LOAD_HISTORY') }} (A_WORKFLOW_HISTORY_KEY, A_WORKFLOW_HISTORY_SOURCE_KEY, A_TASK_HISTORY_KEY, TASK_NAME, TASK_START, TASK_END, WORKFLOW_STATUS)
        select distinct wh.a_workflow_history_key
            ,ths.a_workflow_history_source_key
            ,th.a_task_history_key
            ,th.task_name
            ,th.task_start
            ,th.task_end
            ,wh.workflow_status
        from {{ source('control_tables','A_WORKFLOW_HISTORY') }} wh
        join {{ source('control_tables','A_TASK_HISTORY') }} th on wh.a_workflow_history_key = th.a_workflow_history_key and wh.service_name = th.service_name
        join {{ source('control_tables','A_TASK_HISTORY_SOURCE') }} ths on th.a_task_history_key = ths.a_task_history_key and th.service_name = ths.service_name
        where wh.service_name = '{{ var("input_service_name") }}'
        and wh.workflow_name = '{{ var("workflow_name") }}'
        and wh.orchestration_run_id = '{{ var("orchestration_run_id") }}'
        and ths.a_workflow_history_source_key is not null
    {% endset %} 

    {% do run_query(insert_A_MOPDB_LOAD_HISTORY) %}

{% endif %}
{% endmacro %}