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

    system_ombCategory AS (
        SELECT DISTINCT
            s.id AS id,
            '0' AS priority,
            'ombCategory' AS system, -- noqa: RF04
            ext_child.ext.valuecoding.code AS race_code,
            ext_child.ext.valuecoding.display AS race_display
        FROM
            patient AS s,
            UNNEST(s.extension) AS ext_parent (ext),
            UNNEST(ext_parent.ext.extension) AS ext_child (ext)
        WHERE
            ext_parent.ext.url = 'http://hl7.org/fhir/us/core/StructureDefinition/us-core-race'
            AND ext_child.ext.url = 'ombCategory'
            AND ext_child.ext.valuecoding.display != ''
    ),

    system_detailed AS (
        SELECT DISTINCT
            s.id AS id,
            '1' AS priority,
            'detailed' AS system, -- noqa: RF04
            ext_child.ext.valuecoding.code AS race_code,
            ext_child.ext.valuecoding.display AS race_display
        FROM
            patient AS s,
            UNNEST(s.extension) AS ext_parent (ext),
            UNNEST(ext_parent.ext.extension) AS ext_child (ext)
        WHERE
            ext_parent.ext.url = 'http://hl7.org/fhir/us/core/StructureDefinition/us-core-race'
            AND ext_child.ext.url = 'detailed'
            AND ext_child.ext.valuecoding.display != ''
    ),

    union_table AS (
        SELECT
            id,
            priority,
            system,
            race_code,
            race_display
        FROM system_ombCategory
        UNION
        SELECT
            id,
            priority,
            system,
            race_code,
            race_display
        FROM system_detailed
        
        ORDER BY id, priority
    )

    SELECT
        id,
        system,
        race_code,
        race_display
    FROM (
        SELECT
            id,
            system,
            LOWER(
                ARRAY_JOIN(
                    ARRAY_SORT(
                        ARRAY_AGG(
                            race_code
                        )
                    ), '; '
                )
            )
                AS race_code,
            LOWER(
                ARRAY_JOIN(
                    ARRAY_SORT(
                        ARRAY_AGG(
                            race_display
                        )
                    ), '; '
                )
            ) AS race_display,
            ROW_NUMBER()
                OVER (
                    PARTITION BY id
                    ORDER BY priority ASC
                ) AS available_priority
        FROM union_table
        GROUP BY id, system, priority
    )
    WHERE available_priority = 1
);

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

CREATE TABLE core__patient_ext_ethnicity AS (
    WITH

    system_ombCategory AS (
        SELECT DISTINCT
            s.id AS id,
            '0' AS priority,
            'ombCategory' AS system, -- noqa: RF04
            ext_child.ext.valuecoding.code AS ethnicity_code,
            ext_child.ext.valuecoding.display AS ethnicity_display
        FROM
            patient AS s,
            UNNEST(s.extension) AS ext_parent (ext),
            UNNEST(ext_parent.ext.extension) AS ext_child (ext)
        WHERE
            ext_parent.ext.url = 'http://hl7.org/fhir/us/core/StructureDefinition/us-core-ethnicity'
            AND ext_child.ext.url = 'ombCategory'
            AND ext_child.ext.valuecoding.display != ''
    ),

    system_detailed AS (
        SELECT DISTINCT
            s.id AS id,
            '1' AS priority,
            'detailed' AS system, -- noqa: RF04
            ext_child.ext.valuecoding.code AS ethnicity_code,
            ext_child.ext.valuecoding.display AS ethnicity_display
        FROM
            patient AS s,
            UNNEST(s.extension) AS ext_parent (ext),
            UNNEST(ext_parent.ext.extension) AS ext_child (ext)
        WHERE
            ext_parent.ext.url = 'http://hl7.org/fhir/us/core/StructureDefinition/us-core-ethnicity'
            AND ext_child.ext.url = 'detailed'
            AND ext_child.ext.valuecoding.display != ''
    ),

    union_table AS (
        SELECT
            id,
            priority,
            system,
            ethnicity_code,
            ethnicity_display
        FROM system_ombCategory
        UNION
        SELECT
            id,
            priority,
            system,
            ethnicity_code,
            ethnicity_display
        FROM system_detailed
        
        ORDER BY id, priority
    )

    SELECT
        id,
        system,
        ethnicity_code,
        ethnicity_display
    FROM (
        SELECT
            id,
            system,
            LOWER(
                ARRAY_JOIN(
                    ARRAY_SORT(
                        ARRAY_AGG(
                            ethnicity_code
                        )
                    ), '; '
                )
            )
                AS ethnicity_code,
            LOWER(
                ARRAY_JOIN(
                    ARRAY_SORT(
                        ARRAY_AGG(
                            ethnicity_display
                        )
                    ), '; '
                )
            ) AS ethnicity_display,
            ROW_NUMBER()
                OVER (
                    PARTITION BY id
                    ORDER BY priority ASC
                ) AS available_priority
        FROM union_table
        GROUP BY id, system, priority
    )
    WHERE available_priority = 1
);

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


CREATE TABLE core__patient AS
WITH temp_patient AS (
    SELECT DISTINCT
        p.id,
        p.gender,
        p.address,
        cast(from_iso8601_timestamp(p.birthDate) AS date) AS birthDate,
        er.race_display,
        ee.ethnicity_display
    FROM
        patient AS p
    LEFT JOIN core__patient_ext_race AS er ON p.id = er.id
    LEFT JOIN core__patient_ext_ethnicity AS ee ON p.id = ee.id
),

-- Grab a single address to use for this patient, if present
temp_address AS (
    SELECT
        tp.id,
        
        
        
        substr(max(t_address.addr_row.postalcode), 1, 3) AS postalcode3
    FROM
        temp_patient AS tp,
        unnest(tp.address) AS t_address (addr_row)
    GROUP BY tp.id
)

SELECT DISTINCT
    tp.id,
    tp.gender,
    tp.birthDate,
    coalesce(ta.postalcode3, 'cumulus__none') AS postalCode_3,
    concat('Patient/', tp.id) AS subject_ref,
    coalesce(tp.race_display, 'unknown') AS race_display,
    coalesce(tp.ethnicity_display, 'unknown') AS ethnicity_display
FROM
    temp_patient AS tp
LEFT JOIN temp_address AS ta ON tp.id = ta.id

WHERE
    tp.birthDate IS NOT NULL
    AND tp.gender IS NOT NULL;
