-- 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__condition AS
WITH temp_condition AS (
    SELECT
        c.id,
        c.subject.reference AS subject_ref,
        c.encounter.reference AS encounter_ref,
        cca.code,
        cca.system,
        cca.display,
        cast(from_iso8601_timestamp(c.recordedDate) AS date) AS recordedDate,
        date_trunc('week', cast(from_iso8601_timestamp(c."recordedDate") AS date))
            AS recordedDate_week,
        date_trunc('month', cast(from_iso8601_timestamp(c."recordedDate") AS date))
            AS recordedDate_month,
        date_trunc('year', cast(from_iso8601_timestamp(c."recordedDate") AS date))
            AS recordedDate_year
    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,
    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;
