-- #############################################################
-- DocumentReference
-- https://hl7.org/fhir/us/core/StructureDefinition-us-core-documentreference.html

--Each DocumentReference must have:
--    a status
--    a code describing the type of document
--    a document category
--    a patient
--    document referenced (content)
--    the MIME type (i.e. contentType) of the document

--Each DocumentReference must support:
--    a business identifier for the DocumentReference (possibly generated by the transcription system or EHR)
--    date and time the reference was created
--    an author
--    a code identifying the specific details about the format of the document — over and above the content’s MIME type
--    the patient encounter that is being referenced
--    clinically relevant date

CREATE TABLE core__documentreference AS
WITH temp_documentreference AS (
    SELECT DISTINCT
        dr.type,
        dr.status,
        dr.context,
        dr.subject.reference AS subject_ref,
        dr.id AS doc_id,
        date(
            from_iso8601_timestamp(dr.context.period."start")
        ) AS author_date,
        concat('DocumentReference/', dr.id) AS doc_ref
    FROM documentreference AS dr
)

SELECT DISTINCT
    type_coding.type_row AS doc_type,
    coalesce(type_coding.type_row.code, 'None') AS doc_type_code,
    CASE
        WHEN
            type_coding.type_row.display IS NOT NULL
            THEN replace(type_coding.type_row.display, ',')
        ELSE type_row.code
    END AS doc_type_display,
    tdr.status,
    context_encounter.encounter.reference AS encounter_ref,
    date_trunc('day', tdr.author_date) AS author_date,
    date_trunc('week', tdr.author_date) AS author_week,
    date_trunc('month', tdr.author_date) AS author_month,
    date_trunc('year', tdr.author_date) AS author_year,
    tdr.subject_ref,
    tdr.doc_id,
    tdr.doc_ref
FROM temp_documentreference AS tdr,
    unnest(context.encounter) AS context_encounter (encounter), --noqa
    unnest(type.coding) AS type_coding (type_row)
WHERE author_date BETWEEN date('2016-06-01') AND current_date;

-- count *group by* DocumentReference.type
CREATE TABLE core__count_documentreference_month AS
WITH powerset AS (
    SELECT
        count(DISTINCT d.subject_ref) AS cnt_subject,
        count(DISTINCT d.encounter_ref) AS cnt_encounter,
        count(DISTINCT d.doc_id) AS cnt_document,
        d.doc_type_display,
        d.author_month,
        e.enc_class.display AS enc_class_code
    FROM core__documentreference AS d, core__encounter AS e
    WHERE d.encounter_ref = e.encounter_ref
    GROUP BY cube(d.doc_type_display, d.author_month, e.enc_class)
)

SELECT DISTINCT
    cnt_document AS cnt,
    author_month,
    enc_class_code,
    doc_type_display
FROM powerset
WHERE cnt_subject >= 10
ORDER BY cnt_document DESC, enc_class_code ASC;
