-- 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 Organization profile.
-- BUT ADDING:
-- * the `identifier` field
-- * the `type` field, because it's helpful for classification
-- * the `alias` field, because it's similarly useful as name
-- * the `partOf` field, because it could be helpful for classification
--
-- US Core profile for reference:
-- * https://hl7.org/fhir/us/core/STU4/StructureDefinition-us-core-organization.html

CREATE TABLE core__organization AS
WITH flat AS (
    SELECT
        src.id,
        src.alias,
        src.active,
        src.name,
        src.partOf.reference AS part_of_ref
    FROM organization 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 organization 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_type.code AS type_code,
    dn_type.system AS type_system,
    dn_type.display AS type_display,

    flat.name,
    -- Combine name and aliases into one big comma delineated list, for convenience of searching
    array_join(
        CASE
        WHEN flat.name IS NULL AND flat.alias IS NULL THEN NULL
        WHEN flat.name IS NULL THEN flat.alias
        WHEN flat.alias IS NULL THEN [flat.name]
        ELSE [flat.name] || flat.alias
    END, ', '
    ) AS "alias", -- noqa: RF06

    concat('Organization/', flat.id) AS organization_ref,
    flat.part_of_ref

FROM flat
LEFT JOIN core__organization_dn_type AS dn_type ON flat.id = dn_type.id
LEFT JOIN identifiers ON flat.id = identifiers.id;
