-- 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 core__allergyintolerance_dn_clinical_status AS (
    WITH

    system_clinicalStatus_0 AS (
        SELECT DISTINCT
            s.id AS id,
            0 AS row,
            '0' AS priority,
            u.coding.code,
            u.coding.display,
            u.coding.system,
            u.coding.userSelected
        FROM
            allergyintolerance AS s,
            UNNEST(s.clinicalStatus.coding) AS u (coding)
        WHERE
            REGEXP_LIKE(u.coding.system, '^http://terminology\.hl7\.org/CodeSystem/allergyintolerance-clinical$')
    ), --noqa: LT07

    union_table AS (
        SELECT
            id,
            row,
            priority,
            system,
            code,
            display,
            userSelected
        FROM system_clinicalStatus_0
        
    ),

    partitioned_table AS (
        SELECT
            id,
            row,
            code,
            system,
            display,
            userSelected,
            priority,
            ROW_NUMBER()
                OVER (
                    PARTITION BY id
                    ORDER BY priority ASC, code ASC
                ) AS available_priority
        FROM union_table
        GROUP BY
            id, row, priority, system, code, display, userSelected
    )

    SELECT
        id,
        code,
        system,
        display,
        userSelected
    FROM partitioned_table
    WHERE available_priority = 1
);


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

CREATE TABLE core__allergyintolerance_dn_verification_status AS (
    WITH

    system_verificationStatus_0 AS (
        SELECT DISTINCT
            s.id AS id,
            0 AS row,
            '0' AS priority,
            u.coding.code,
            u.coding.display,
            u.coding.system,
            u.coding.userSelected
        FROM
            allergyintolerance AS s,
            UNNEST(s.verificationStatus.coding) AS u (coding)
        WHERE
            REGEXP_LIKE(u.coding.system, '^http://terminology\.hl7\.org/CodeSystem/allergyintolerance-verification$')
    ), --noqa: LT07

    union_table AS (
        SELECT
            id,
            row,
            priority,
            system,
            code,
            display,
            userSelected
        FROM system_verificationStatus_0
        
    ),

    partitioned_table AS (
        SELECT
            id,
            row,
            code,
            system,
            display,
            userSelected,
            priority,
            ROW_NUMBER()
                OVER (
                    PARTITION BY id
                    ORDER BY priority ASC, code ASC
                ) AS available_priority
        FROM union_table
        GROUP BY
            id, row, priority, system, code, display, userSelected
    )

    SELECT
        id,
        code,
        system,
        display,
        userSelected
    FROM partitioned_table
    WHERE available_priority = 1
);


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

CREATE TABLE core__allergyintolerance_dn_code AS (
    WITH

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

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


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

CREATE TABLE IF NOT EXISTS "main"."core__allergyintolerance_dn_reaction_substance"
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__allergyintolerance_dn_reaction_manifestation AS (
    WITH

    flattened_rows AS (
        SELECT DISTINCT
            t.id AS id,
            ROW_NUMBER() OVER (PARTITION BY id) AS row,
            r."manifestation"
        FROM
            allergyintolerance AS t,
            UNNEST(t."reaction") AS parent (r)
    ),

    child_flattened_rows AS (
        SELECT DISTINCT
            s.id,
            s.row, -- keep the parent row number
            u."manifestation"
        FROM
            flattened_rows AS s,
            UNNEST(s.manifestation) AS u ("manifestation")
    ),

    system_manifestation_0 AS (
        SELECT DISTINCT
            s.id AS id,
            s.row,
            u.coding.code,
            u.coding.display,
            u.coding.system,
            u.coding.userSelected
        FROM
            child_flattened_rows AS s,
            UNNEST(s.manifestation.coding) AS u (coding)
    ), --noqa: LT07

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


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




CREATE TABLE core__allergyintolerance AS
WITH temp_allergyintolerance AS (
    SELECT
        a.id,
        a.type,
        a.category,
        a.criticality,
        a.patient.reference AS patient_ref,
        a.encounter.reference AS encounter_ref,
        date(from_iso8601_timestamp(a.recordedDate)) AS recordedDate,
        date_trunc('week', date(from_iso8601_timestamp(a."recordedDate")))
            AS recordedDate_week,
        date_trunc('month', date(from_iso8601_timestamp(a."recordedDate")))
            AS recordedDate_month,
        date_trunc('year', date(from_iso8601_timestamp(a."recordedDate")))
            AS recordedDate_year
    FROM allergyintolerance AS a
),

temp_category AS (
    SELECT
        a.id,
        t.category
    FROM
        allergyintolerance AS a,
        unnest(a.category) AS t (category)
),

flattened_reaction AS (SELECT DISTINCT
            t.id AS id,
            ROW_NUMBER() OVER (PARTITION BY id) AS row,
            r."reaction"
        FROM
            allergyintolerance AS t,
            UNNEST(t."reaction") AS r ("reaction")),

temp_reaction AS (
    SELECT
        r.id,
        r.row,
        dn_subs.code AS substance_code,
        dn_subs.system AS substance_system,
        dn_subs.display AS substance_display,
        dn_man.code AS manifestation_code,
        dn_man.system AS manifestation_system,
        dn_man.display AS manifestation_display,
        r.reaction.severity AS severity
    FROM flattened_reaction AS r
    LEFT JOIN core__allergyintolerance_dn_reaction_substance AS dn_subs
        ON r.id = dn_subs.id AND r.row = dn_subs.row
    LEFT JOIN core__allergyintolerance_dn_reaction_manifestation AS dn_man
        ON r.id = dn_man.id AND r.row = dn_man.row
)

SELECT
    ta.id,
    dn_cstat.code AS clinicalStatus_code,
    dn_vstat.code AS verificationStatus_code,
    ta.type,
    tcat.category,
    ta.criticality,

    dn_code.code AS code_code,
    dn_code.system AS code_system,
    dn_code.display AS code_display,
    ta.recordedDate,
    ta.recordedDate_week,
    ta.recordedDate_month,
    ta.recordedDate_year,
    tr.row AS reaction_row,
    tr.substance_code AS reaction_substance_code,
    tr.substance_system AS reaction_substance_system,
    tr.substance_display AS reaction_substance_display,
    tr.manifestation_code AS reaction_manifestation_code,
    tr.manifestation_system AS reaction_manifestation_system,
    tr.manifestation_display AS reaction_manifestation_display,
    tr.severity AS reaction_severity,

    concat('AllergyIntolerance/', ta.id) AS allergyintolerance_ref,
    ta.patient_ref,
    ta.encounter_ref

FROM temp_allergyintolerance AS ta
LEFT JOIN temp_reaction AS tr ON ta.id = tr.id
LEFT JOIN core__allergyintolerance_dn_code AS dn_code ON ta.id = dn_code.id
LEFT JOIN core__allergyintolerance_dn_clinical_status AS dn_cstat ON ta.id = dn_cstat.id
LEFT JOIN core__allergyintolerance_dn_verification_status AS dn_vstat
    ON ta.id = dn_vstat.id
LEFT JOIN temp_category AS tcat ON ta.id = tcat.id;
