{% import 'core_utils.jinja' as utils %}

CREATE TABLE core__medicationrequest AS
WITH

tmp_dn_dosage_text AS (
    SELECT
        mr.id,
        {{- utils.nullable_cols(
            'medicationrequest',
            'u',
            [
                ('dosageInstruction', 'text', 'dosageInstruction_text'),
            ],
            schema
        ) }}
    FROM medicationrequest AS mr,
        UNNEST(mr.dosageInstruction) AS u (dosageInstruction)
    WHERE u.dosageInstruction.text IS NOT NULL
),

temp_mr AS (
    SELECT 
        {{- utils.basic_cols(
                'medicationrequest',
                'mr',
                [
                    'id', 
                    'status', 
                    'intent',
                ]
            ) 
        }},
        {{- utils.date_cols_from_str(
                'medicationrequest',
                'mr',
                ['authoredOn'],
                schema
            ) 
        }},
        {{- utils.truncate_date_cols(
                'medicationrequest',
                'mr',
                [
                    ('authoredOn', 'month'),
                ],
                schema
            ) 
        }},
        {{- utils.nullable_cols(
                'medicationrequest',

                'mr',
                [
                    'reportedBoolean',
                    ('subject', 'reference', 'subject_ref'),
                    ('encounter', 'reference', 'encounter_ref'),
                ],
                schema
        ) -}},
        mrc.code AS category_code,
        mrc.code_system AS category_code_system,
        mrm.code AS medication_code,
        mrm.code_system AS medication_code_system,
        mrm.display AS medication_display,
        mrdt.dosageInstruction_text
    FROM medicationrequest AS mr
    LEFT JOIN core__medicationrequest_dn_category AS mrc ON mr.id = mrc.id
    LEFT JOIN core__medicationrequest_dn_inline_code AS mrm ON mr.id = mrm.id
    LEFT JOIN tmp_dn_dosage_text AS mrdt ON mr.id = mrdt.id
    WHERE mrm.code_system = 'http://www.nlm.nih.gov/research/umls/rxnorm'
)

SELECT
    mr.id,
    mr.status,
    mr.intent,
    mr.category_code,
    mr.category_code_system,
    mr.reportedBoolean,
    mr.medication_code_system,
    mr.medication_code,
    mr.medication_display,
    mr.authoredOn,
    mr.authoredOn_month,
    mr.dosageInstruction_text,
    mr.subject_ref,
    mr.encounter_ref
FROM temp_mr AS mr
