{% import 'core_utils.jinja' as utils -%}
{% import 'syntax.sql.jinja' as syntax -%}

CREATE TABLE core__medication AS (
    WITH

    mr_basics AS (
        SELECT DISTINCT
            {{- utils.basic_cols(
                    'medicationrequest',
                    'mr',
                    [
                        'id'
                    ],
                )
            }},
            {{- utils.nullable_cols(
                    'medicationrequest',
                    'mr',
                    [
                        ('encounter', 'reference', 'encounter_ref'),
                        ('subject', 'reference', 'patient_ref'),
                        ('medicationReference', 'reference', 'med_ref'),
                    ],
                    schema
                )
            }}
        FROM medicationrequest AS mr
    ),

    contained_refs AS (
        SELECT DISTINCT
            mr.id,
            substring(mr.med_ref, 2) AS medication_id
        FROM mr_basics AS mr
        WHERE mr.med_ref IS NOT NULL AND {{ syntax.like('mr.med_ref', '#%') }}
    ),

    external_refs AS (
        SELECT DISTINCT
            mr.id,
            substring(mr.med_ref, 12) AS medication_id
        FROM mr_basics AS mr
        WHERE mr.med_ref IS NOT NULL AND {{ syntax.like('mr.med_ref', 'Medication/%') }}
    )

    {# Internal: medication data from inline ETL extraction.
    95% of the time, this dataset is the 'correct' dataset for Cerner.
    It may not be present in EPIC datasets. #}
    SELECT
        mr.id,
        mr.encounter_ref,
        mr.patient_ref,
        mric.code,
        mric.display,
        mric.code_system,
        mric.userSelected
    FROM mr_basics AS mr
    INNER JOIN core__medicationrequest_dn_inline_code AS mric ON mr.id = mric.id

    {# Contained: medication reference into contained resources.
    We've also seen this in Cerner. Though in the cases we've seen this, it's usuall
    a very lightly fleshed out resource, with only code.text and no codings. #}
    UNION
    SELECT
        mr.id,
        mr.encounter_ref,
        mr.patient_ref,
        mrcc.code,
        mrcc.display,
        mrcc.code_system,
        mrcc.userSelected
    FROM mr_basics AS mr
    INNER JOIN contained_refs AS cr ON mr.id = cr.id
    INNER JOIN core__medicationrequest_dn_contained_code AS mrcc
        ON cr.id = mrcc.id AND cr.medication_id = mrcc.contained_id
    WHERE mrcc.resource_type = 'Medication'

    {# External: medication by reference from external medications table.
    This is generally how we expect EPIC to provide medication data. #}
    UNION
    SELECT
        mr.id,
        mr.encounter_ref,
        mr.patient_ref,
        mc.code,
        mc.display,
        mc.code_system,
        mc.userSelected
    FROM mr_basics AS mr
    INNER JOIN external_refs AS er ON mr.id = er.id
    INNER JOIN core__medication_dn_code AS mc ON er.medication_id = mc.id
);
