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

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




-- This table includes all fields of interest to the US Core Practitioner profile.
-- BUT ADDING:
-- * the `identifier` field
-- * the `active` field, because it lets us know to even look at the row
-- * the `qualification.code` field, because it could be helpful for classification
--
-- US Core profile for reference:
-- * https://hl7.org/fhir/us/core/STU4/StructureDefinition-us-core-practitioner.html

CREATE TABLE core__practitioner AS
WITH flat AS (
    SELECT
        src.id,
        src.active
    FROM practitioner AS src
),

identifiers AS (WITH
        data_and_row_num AS (
            SELECT
                t.id AS id,
                generate_subscripts(t."identifier", 1) AS row,
                UNNEST(t."identifier") AS "identifier" -- must unnest in SELECT here
            FROM practitioner AS t
        )
        SELECT
            id,
            row,
            "identifier"
        FROM data_and_row_num)

SELECT
    flat.id,

    identifiers.identifier.value AS identifier_value,
    identifiers.identifier.system AS identifier_system,

    flat.active,

    dn_code.code AS qualification_code_code,
    dn_code.system AS qualification_code_system,
    dn_code.display AS qualification_code_display,

    concat('Practitioner/', flat.id) AS practitioner_ref

FROM flat
LEFT JOIN core__practitioner_dn_qualification_code AS dn_code ON flat.id = dn_code.id
LEFT JOIN identifiers ON flat.id = identifiers.id;
