-- 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__diagnosticreport_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 diagnosticreport 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__diagnosticreport_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
            diagnosticreport 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__diagnosticreport_dn_conclusioncode"
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
);

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




-- This table includes all fields of interest to the US Core DiagnosticReport profiles.
-- EXCEPT FOR:
-- * the 'presentedForm' field, which is an attachment array that is stripped out by the ETL.
-- * the `reporter` field, simply due to it not likely being interesting to consumers
--   and being an array field, which would require a lot of row duplication.
--
-- AND ADDING:
-- * the `conclusionCode` field, because it has clinical relevance
--
-- US Core profiles for reference:
-- * https://hl7.org/fhir/us/core/STU4/StructureDefinition-us-core-diagnosticreport-lab.html
-- * https://hl7.org/fhir/us/core/STU4/StructureDefinition-us-core-diagnosticreport-note.html

CREATE TABLE core__diagnosticreport AS
WITH temp_diagnosticreport AS (
    SELECT
        d.id,
        d.status,
        d.subject.reference AS subject_ref,
        d.encounter.reference AS encounter_ref,
        date_trunc('day', cast(from_iso8601_timestamp(d."effectiveDateTime") AS date))
            AS effectiveDateTime_day,
        date_trunc('week', cast(from_iso8601_timestamp(d."effectiveDateTime") AS date))
            AS effectiveDateTime_week,
        date_trunc('month', cast(from_iso8601_timestamp(d."effectiveDateTime") AS date))
            AS effectiveDateTime_month,
        date_trunc('year', cast(from_iso8601_timestamp(d."effectiveDateTime") AS date))
            AS effectiveDateTime_year,
        date_trunc('day', cast(from_iso8601_timestamp(d."effectivePeriod"."start") AS date))
            AS effectivePeriod_start_day,
        date_trunc('week', cast(from_iso8601_timestamp(d."effectivePeriod"."start") AS date))
            AS effectivePeriod_start_week,
        date_trunc('month', cast(from_iso8601_timestamp(d."effectivePeriod"."start") AS date))
            AS effectivePeriod_start_month,
        date_trunc('year', cast(from_iso8601_timestamp(d."effectivePeriod"."start") AS date))
            AS effectivePeriod_start_year,
        date_trunc('day', cast(from_iso8601_timestamp(d."effectivePeriod"."end") AS date))
            AS effectivePeriod_end_day,
        date_trunc('week', cast(from_iso8601_timestamp(d."effectivePeriod"."end") AS date))
            AS effectivePeriod_end_week,
        date_trunc('month', cast(from_iso8601_timestamp(d."effectivePeriod"."end") AS date))
            AS effectivePeriod_end_month,
        date_trunc('year', cast(from_iso8601_timestamp(d."effectivePeriod"."end") AS date))
            AS effectivePeriod_end_year,
        date_trunc('day', cast(from_iso8601_timestamp(d."issued") AS date))
            AS issued_day,
        date_trunc('week', cast(from_iso8601_timestamp(d."issued") AS date))
            AS issued_week,
        date_trunc('month', cast(from_iso8601_timestamp(d."issued") AS date))
            AS issued_month,
        date_trunc('year', cast(from_iso8601_timestamp(d."issued") AS date))
            AS issued_year
    FROM diagnosticreport AS d
),

temp_result AS (
    WITH
        data_and_row_num AS (
            SELECT
                t.id AS id,
                generate_subscripts(t."result", 1) AS row,
                UNNEST(t."result") AS data -- must unnest in SELECT here
            FROM diagnosticreport AS t
        )
        SELECT
            id,
            row,
            data."reference"
        FROM data_and_row_num
)

SELECT
    td.id,
    td.status,

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

    dn_code.code AS code_code,
    dn_code.system AS code_system,
    dn_code.display AS code_display,

    td.effectiveDateTime_day,
    td.effectiveDateTime_week,
    td.effectiveDateTime_month,
    td.effectiveDateTime_year,

    td.effectivePeriod_start_day,
    td.effectivePeriod_start_week,
    td.effectivePeriod_start_month,
    td.effectivePeriod_start_year,

    td.effectivePeriod_end_day,
    td.effectivePeriod_end_week,
    td.effectivePeriod_end_month,
    td.effectivePeriod_end_year,

    td.issued_day,
    td.issued_week,
    td.issued_month,
    td.issued_year,

    dn_conclusion.code AS conclusionCode_code,
    dn_conclusion.system AS conclusionCode_system,
    dn_conclusion.display AS conclusionCode_display,

    concat('DiagnosticReport/', td.id) AS diagnosticreport_ref,
    td.subject_ref,
    td.encounter_ref,
    tr.reference AS result_ref

FROM temp_diagnosticreport AS td
LEFT JOIN core__diagnosticreport_dn_code AS dn_code ON td.id = dn_code.id
LEFT JOIN core__diagnosticreport_dn_category AS dn_category ON td.id = dn_category.id
LEFT JOIN core__diagnosticreport_dn_conclusioncode AS dn_conclusion
    ON td.id = dn_conclusion.id
LEFT JOIN temp_result AS tr ON td.id = tr.id;
