/*
    Dispensing by VTM or VMP
    ========================

    Purpose:
    Summarise dispensed items, patients, and quantity for a medicine group
    using national dispensing data.

    Data source:
    NATIONAL.GPMED."MedicinesDispensedInPrimarycare"

    Notes:
    - Dispensing data is official/payment-oriented and usually lags prescribing.
    - Set either VTM_SNOMED_CODE or VMP_SNOMED_CODE. Leave the other as NULL.
    - ProcessingPeriodDate is a month-level period date.
*/

SET START_PERIOD = '2025-04-01';
SET END_PERIOD = '2026-03-31';
SET VTM_SNOMED_CODE = NULL;
SET VMP_SNOMED_CODE = 'REPLACE_WITH_VMP_SNOMED_CODE';

WITH products AS (
    -- Expands the selected VTM/VMP into product-level dm+d codes found in GPMED.
    SELECT DISTINCT
        "ProductSnomedCode",
        "ProductDescription",
        "TherapeuticMoietyName",
        "BNFCode"
    FROM DATA_HUB.DWH."DimMedicineAndDevice"
    WHERE ($VTM_SNOMED_CODE IS NOT NULL AND "TherapeuticMoietySnomedCode" = $VTM_SNOMED_CODE)
       OR ($VMP_SNOMED_CODE IS NOT NULL AND "MedicinalLatestSnomedCode" = $VMP_SNOMED_CODE)
       OR ($VMP_SNOMED_CODE IS NOT NULL AND "ProductSnomedCode" = $VMP_SNOMED_CODE)
),
practices AS (
    -- Restricts output to active Norfolk and Suffolk parent GP practices.
    SELECT DISTINCT
        "OrganisationCode" AS "PracticeCode",
        "OrganisationName" AS "PracticeName",
        "PCNName",
        "PlaceName",
        "AllianceName"
    FROM DATA_HUB.DWH."DimOrganisationAndSite"
    WHERE "OrganisationSubType" = 'GP Practice'
      AND "IsSiteActive" = 'Yes'
      AND "IsSiteNorfolkAndSuffolk" = 'Yes'
      AND "SiteCode" = "OrganisationCode"
)
SELECT
    gpm."ProcessingPeriodDate" AS "PeriodDate",
    p."PracticeCode",
    p."PracticeName",
    p."PCNName",
    p."PlaceName",
    p."AllianceName",
    prod."TherapeuticMoietyName",
    COUNT(DISTINCT gpm."PatientPseudonym") AS "Patients",
    SUM(gpm."ItemCount") AS "Items",
    SUM(gpm."PaidQuantity") AS "PaidQuantity"
FROM NATIONAL.GPMED."MedicinesDispensedInPrimarycare" gpm
INNER JOIN products prod
    ON gpm."PaiddmdCode" = prod."ProductSnomedCode"
INNER JOIN practices p
    ON gpm."CostCentreODSCode" = p."PracticeCode"
WHERE gpm."ProcessingPeriodDate" BETWEEN $START_PERIOD AND $END_PERIOD
  AND gpm."PatientPseudonym" IS NOT NULL
GROUP BY
    gpm."ProcessingPeriodDate",
    p."PracticeCode",
    p."PracticeName",
    p."PCNName",
    p."PlaceName",
    p."AllianceName",
    prod."TherapeuticMoietyName"
ORDER BY
    "PeriodDate",
    "PracticeName",
    prod."TherapeuticMoietyName";
