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

CREATE TABLE core__condition AS
WITH temp_condition AS (
    SELECT
         {{- 
            utils.basic_cols(
                'condition',
                'c',
                [
                    'id',
                ]
            ) 
        }},
        {{- 
            utils.nullable_cols(
                'condition',
                'c',
                [
                    ('subject', 'reference', 'subject_ref'),
                    ('encounter', 'reference', 'encounter_ref'),
                ], 
                schema
            ) 
        }},
        {{- 
            utils.basic_cols(
                'core__condition_codable_concepts_all',
                'cca',
                [
                    'code',
                    'system',
                    'display'
                ]
            ) 
        }},
        {{- 
            utils.date_cols_from_str(
                'condition',
                'c',
                ['recordedDate'],
                schema
            ) 
        }},
        {{- 
            utils.truncate_date_cols(
                'condition',
                'c',
                [
                    ('recordedDate', 'week'),
                    ('recordedDate', 'month'),
                    ('recordedDate', 'year'),
                ],
                schema
            ) 
        }}
    FROM condition AS c
    LEFT JOIN core__condition_codable_concepts_all AS cca ON c.id = cca.id
)

SELECT
    tc.id,
    cdc.code AS category_code,
    cdc.system AS category_system,
    cdc.display AS category_display,
    tc.code,
    tc.system,
    tc.display AS code_display,
    tc.subject_ref,
    tc.encounter_ref,
    concat('Condition/', tc.id) AS condition_ref,
    tc.recordedDate,
    tc.recordedDate_week,
    tc.recordedDate_month,
    tc.recordedDate_year,
    {#- We don't expose system for these next two since we filter
        down to a single system in the denormalization table #}
    cdcs.code AS clinicalStatus_code,
    cdvs.code AS verificationStatus_code
FROM temp_condition AS tc
LEFT JOIN core__condition_dn_category AS cdc ON tc.id = cdc.id
LEFT JOIN core__condition_dn_clinical_status AS cdcs ON tc.id = cdcs.id
LEFT JOIN core__condition_dn_verification_status AS cdvs ON tc.id = cdvs.id;
