-- noqa: disable=all
-- This sql was autogenerated as a reference example using the library
-- CLI. Its format is tied to the specific database it was run against,
-- and it may not be correct for all databases. Use the CLI's build 
-- option to derive the best SQL for your dataset.

-- ###########################################################

CREATE TABLE IF NOT EXISTS "main"."core__medication_dn_code"
AS (
    SELECT * FROM (
        VALUES
        (cast(NULL AS varchar),cast(NULL AS bigint),cast(NULL AS varchar),cast(NULL AS varchar),cast(NULL AS varchar),cast(NULL AS boolean))
    )
        AS t ("id","row","code","system","display","userSelected")
    WHERE 1 = 0 -- ensure empty table
);

-- ###########################################################

CREATE TABLE core__medicationrequest_dn_inline_code AS (
    WITH

    system_medicationCodeableConcept_0 AS (
        SELECT DISTINCT
            s.id AS id,
            0 AS row,
            u.coding.code,
            u.coding.display,
            u.coding.system,
            u.coding.userSelected
        FROM
            medicationrequest AS s,
            UNNEST(s.medicationCodeableConcept.coding) AS u (coding)
    ), --noqa: LT07

    union_table AS (
        SELECT
            id,
            row,
            system,
            code,
            display,
            userSelected
        FROM system_medicationCodeableConcept_0
        
    )
    SELECT
        id,
        code,
        system,
        display,
        userSelected
    FROM union_table
);


-- ###########################################################

CREATE TABLE IF NOT EXISTS "main"."core__medicationrequest_dn_contained_code"
AS (
    SELECT * FROM (
        VALUES
        (cast(NULL AS varchar),cast(NULL AS bigint),cast(NULL AS varchar),cast(NULL AS varchar),cast(NULL AS varchar),cast(NULL AS boolean),cast(NULL AS varchar),cast(NULL AS varchar))
    )
        AS t ("id","row","code","system","display","userSelected","contained_id","resource_type")
    WHERE 1 = 0 -- ensure empty table
);

-- ###########################################################

CREATE TABLE core__medicationrequest_dn_category AS (
    WITH

    flattened_rows AS (
        WITH
        data_and_row_num AS (
            SELECT
                t.id AS id,
                generate_subscripts(t."category", 1) AS row,
                UNNEST(t."category") AS "category" -- must unnest in SELECT here
            FROM medicationrequest AS t
        )
        SELECT
            id,
            row,
            "category"
        FROM data_and_row_num
    ),

    system_category_0 AS (
        SELECT DISTINCT
            s.id AS id,
            s.row,
            u.coding.code,
            u.coding.display,
            u.coding.system,
            u.coding.userSelected
        FROM
            flattened_rows AS s,
            UNNEST(s.category.coding) AS u (coding)
    ), --noqa: LT07

    union_table AS (
        SELECT
            id,
            row,
            system,
            code,
            display,
            userSelected
        FROM system_category_0
        
    )
    SELECT
        id,
        row,
        code,
        system,
        display,
        userSelected
    FROM union_table
);


-- ###########################################################

CREATE TABLE core__medicationrequest AS (
    WITH

    mr_basics AS (
        SELECT DISTINCT
        mr.id,
        mr.status,
        mr.intent,
        mr.reportedBoolean,
        mr.reportedReference.reference AS reported_ref,
        mr.encounter.reference AS encounter_ref,
        mr.subject.reference AS subject_ref,
        mr.medicationReference.reference AS med_ref,
        cast(from_iso8601_timestamp(mr.authoredOn) AS date) AS authoredOn,
        date_trunc('month', cast(from_iso8601_timestamp(mr."authoredOn") AS date))
            AS authoredOn_month
        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 REGEXP_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 REGEXP_LIKE(mr.med_ref, '^Medication/.*$')
    ),

    unified_codes AS (
        
        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

        
        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'

        
        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
    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
);
