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

CREATE TABLE core__medicationrequest AS (
    WITH

    mr_basics AS (
        SELECT DISTINCT
            {{- utils.basic_cols(
                    'medicationrequest',
                    'mr',
                    [
                        'id',
                        'status',
                        'intent'
                    ],
                )
            }},
            {{- utils.nullable_cols(
                    'medicationrequest',
                    'mr',
                    [
                        'reportedBoolean',
                        ('reportedReference', 'reference', 'reported_ref'),
                        ('encounter', 'reference', 'encounter_ref'),
                        ('subject', 'reference', 'subject_ref'),
                        ('medicationReference', 'reference', 'med_ref'),
                        ('requester', 'reference', 'requester_ref'),
                    ],
                    schema
                )
            }},
            {{- utils.date_cols_from_str(
                    'medicationrequest',
                    'mr',
                    ['authoredOn'],
                    schema
                )
            }},
            {{- utils.truncate_date_cols(
                    'medicationrequest',
                    'mr',
                    [
                        ('authoredOn', 'month'),
                    ],
                    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/%') }}
    ),

    unified_codes AS (
        {# 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,
            mric.code AS medication_code,
            mric.system AS medication_system,
            mric.display AS medication_display
        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 usually
        a very lightly fleshed out resource, with only code.text and no codings. #}
        UNION
        SELECT
            mr.id,
            mrcc.code AS medication_code,
            mrcc.system AS medication_system,
            mrcc.display AS medication_display
        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,
            mc.code AS medication_code,
            mc.system AS medication_system,
            mc.display AS medication_display
        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
    )

    SELECT
        mr.id,
        mr.status,
        mr.intent,

        mrc.code AS category_code,
        mrc.system AS category_system,
        mrc.display AS category_display,

        mr.reportedBoolean,
        mr.reported_ref,

        uc.medication_code,
        uc.medication_system,
        uc.medication_display,

        mr.authoredOn,
        mr.authoredOn_month,

        concat('MedicationRequest/', mr.id) AS medicationrequest_ref,
        mr.subject_ref,
        mr.encounter_ref,
        mr.requester_ref
    FROM mr_basics AS mr
    LEFT JOIN unified_codes AS uc ON mr.id = uc.id
    LEFT JOIN core__medicationrequest_dn_category AS mrc ON mr.id = mrc.id
);
