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

-- This table includes all fields of interest to the US Core Specimen profile.
-- BUT ADDING:
-- * the `status` field, because it seems useful
--
-- US Core profile for reference:
-- * http://hl7.org/fhir/us/core/STU6.1/StructureDefinition-us-core-specimen.html

CREATE TABLE core__specimen AS
WITH temp_specimen AS (
    SELECT
        {{- utils.basic_cols('specimen', 'src', ['id']) }},
        {{-
            utils.nullable_cols(
                'specimen',
                'src',
                [
                    'status',
                    ('subject', 'reference', 'subject_ref'),
                ],
                schema
            )
        }}
    FROM specimen 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,

    concat('Specimen/', src.id) AS specimen_ref,
    src.subject_ref

FROM temp_specimen AS src
LEFT JOIN core__specimen_dn_type AS dn_type ON src.id = dn_type.id;
