/*
    Human-readable prescribing detail
    =================================

    Purpose:
    Return row-level prescribing detail with medicine and organisation codes
    replaced by useful names.

    Use this after an aggregate measure finds a cohort that needs checking.
    Keep the output explicit. Avoid SELECT rx.* in shared audit extracts.
*/

SET START_DATE = '2025-04-01';
SET END_DATE = '2026-03-31';
SET BNF_PREFIX = '0501';

WITH practices AS (
    -- Default reporting geography: active Norfolk and Suffolk parent GP practices.
    SELECT
        "OrganisationCode",
        MIN("OrganisationName") AS "OrganisationName",
        MIN("PCNName") AS "PCNName",
        MIN("PlaceName") AS "PlaceName",
        MIN("AllianceName") AS "AllianceName"
    FROM DATA_HUB.DWH."DimOrganisationAndSite"
    WHERE "OrganisationSubType" = 'GP Practice'
      AND "IsSiteActive" = 'Yes'
      AND "IsSiteNorfolkAndSuffolk" = 'Yes'
      AND "SiteCode" = "OrganisationCode"
    GROUP BY "OrganisationCode"
),
organisations AS (
    -- Broader organisation lookup for prescribers/providers that are not GP practices.
    SELECT
        "OrganisationCode",
        MIN("OrganisationName") AS "OrganisationName"
    FROM DATA_HUB.DWH."DimOrganisationAndSite"
    GROUP BY "OrganisationCode"
)
SELECT
    prescribing_org."OrganisationName" AS "PrescribingOrganisationName",
    registered_gp."OrganisationName" AS "RegisteredPracticeName",
    registered_gp."PCNName",
    registered_gp."PlaceName",
    registered_gp."AllianceName",
    rx."PersonKey",
    med."ProductDescription" AS "ProductName",
    med."TherapeuticMoietyName",
    med."BNFCode",
    rx."DateMedicationStart",
    rx."Name" AS "SourceProductName",
    rx."Directions",
    rx."Quantity",
    rx."QuantityUnit",
    rx."IsRepeatPrescription",
    rx."MedicinalControlledDrugStatus",
    rx."EstPrice",
    rx."SourceSystem",
    rx."DataHubCreatedDate",
    rx."SourceRowKey"
FROM REPORTING_DATASETS_ICB.SCRATCHPAD."MEDS__UnifiedPrescribingTable" rx
INNER JOIN DATA_HUB.DWH."DimMedicineAndDevice" med
    ON med."ProductSnomedCode" = rx."SNOMEDCode"
   AND med."BNFCode" LIKE $BNF_PREFIX || '%'
INNER JOIN practices registered_gp
    ON registered_gp."OrganisationCode" = rx."CurrentGeneralPractice"
LEFT JOIN organisations prescribing_org
    ON prescribing_org."OrganisationCode" = rx."OrgCode"
WHERE rx."DateMedicationStart" BETWEEN $START_DATE AND $END_DATE
  AND rx."PersonKey" IS NOT NULL
ORDER BY
    registered_gp."OrganisationName",
    rx."PersonKey",
    rx."DateMedicationStart";
