-- 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.

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



-- There is no US Core EpisodeOfCare profile, but it is still a useful resource,
-- to tie various Encounters together into one time period.

CREATE TABLE core__episodeofcare AS
WITH temp_episodeofcare AS (
    SELECT
        src.id,
        src.status,
        src.patient.reference AS patient_ref,
        date_trunc('day', cast(from_iso8601_timestamp(src."period"."start") AS date))
            AS period_start_day,
        date_trunc('week', cast(from_iso8601_timestamp(src."period"."start") AS date))
            AS period_start_week,
        date_trunc('month', cast(from_iso8601_timestamp(src."period"."start") AS date))
            AS period_start_month,
        date_trunc('year', cast(from_iso8601_timestamp(src."period"."start") AS date))
            AS period_start_year,
        date_trunc('day', cast(from_iso8601_timestamp(src."period"."end") AS date))
            AS period_end_day,
        date_trunc('week', cast(from_iso8601_timestamp(src."period"."end") AS date))
            AS period_end_week,
        date_trunc('month', cast(from_iso8601_timestamp(src."period"."end") AS date))
            AS period_end_month,
        date_trunc('year', cast(from_iso8601_timestamp(src."period"."end") AS date))
            AS period_end_year
    FROM episodeofcare AS src
    WHERE (src.status IS NULL OR src.status <> 'entered-in-error')
)

SELECT
    src.id,
    src.status,

    dn_type.code AS type_code,
    dn_type.system AS type_system,
    dn_type.display AS type_display,

    src.period_start_day,
    src.period_start_week,
    src.period_start_month,
    src.period_start_year,

    src.period_end_day,
    src.period_end_week,
    src.period_end_month,
    src.period_end_year,

    concat('EpisodeOfCare/', src.id) AS episodeofcare_ref,
    src.patient_ref

FROM temp_episodeofcare AS src
LEFT JOIN core__episodeofcare_dn_type AS dn_type ON src.id = dn_type.id;
