{% import 'core_utils.jinja' as utils %}

-- 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
        {{- utils.basic_cols('episodeofcare', 'src', ['id']) }},
        {{-
            utils.nullable_cols(
                'episodeofcare',
                'src',
                [
                    'status',
                    ('patient', 'reference', 'patient_ref'),
                ],
                schema
            )
        }},
        {{-
            utils.truncate_date_cols(
                'episodeofcare',
                'src',
                [
                    ('period', 'start', 'period_start_day', 'day'),
                    ('period', 'start', 'period_start_week', 'week'),
                    ('period', 'start', 'period_start_month', 'month'),
                    ('period', 'start', 'period_start_year', 'year'),
                    ('period', 'end', 'period_end_day', 'day'),
                    ('period', 'end', 'period_end_week', 'week'),
                    ('period', 'end', 'period_end_month', 'month'),
                    ('period', 'end', 'period_end_year', 'year'),
                ],
                schema
            )
        }}
    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;
