-- ==============================================================================
-- Wellness Record: remember the EXACT tests and packages a record ordered.
--
-- Until now a record only knew "lab/radiology were ordered on case X" and read the
-- whole case, so its report and completeness included every test a doctor had
-- ordered separately on that case. These three link tables let the record own its
-- tests:
--
--   patient_wellness_record_packages   which wellness packages were picked
--   patient_wellness_record_lab_tests  the case_lab_tests rows it ordered
--   patient_wellness_record_rad_tests  the case_rad_tests rows it ordered
--
-- Its report then groups them under the package name, and its ABDM link is
-- released when THOSE results are approved.
--
-- Requires wellness_01_schema.sql. Safe to re-run (IF NOT EXISTS / the backfill
-- skips rows already linked).
-- ==============================================================================

CREATE TABLE IF NOT EXISTS `patient_wellness_record_packages` (
  `patient_wellness_record_id` int NOT NULL,
  `wellness_package_id` int NOT NULL,
  PRIMARY KEY (`patient_wellness_record_id`,`wellness_package_id`),
  KEY `IDX_4147EC6223F0247` (`patient_wellness_record_id`),
  KEY `IDX_4147EC69C0E3E42` (`wellness_package_id`),
  CONSTRAINT `FK_4147EC6223F0247` FOREIGN KEY (`patient_wellness_record_id`) REFERENCES `patient_wellness_records` (`id`) ON DELETE CASCADE,
  CONSTRAINT `FK_4147EC69C0E3E42` FOREIGN KEY (`wellness_package_id`) REFERENCES `wellness_packages` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `patient_wellness_record_lab_tests` (
  `patient_wellness_record_id` int NOT NULL,
  `case_laboratory_id` int NOT NULL,
  PRIMARY KEY (`patient_wellness_record_id`,`case_laboratory_id`),
  KEY `IDX_4F86DAE6223F0247` (`patient_wellness_record_id`),
  KEY `IDX_4F86DAE648C3B446` (`case_laboratory_id`),
  CONSTRAINT `FK_4F86DAE6223F0247` FOREIGN KEY (`patient_wellness_record_id`) REFERENCES `patient_wellness_records` (`id`) ON DELETE CASCADE,
  CONSTRAINT `FK_4F86DAE648C3B446` FOREIGN KEY (`case_laboratory_id`) REFERENCES `case_lab_tests` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `patient_wellness_record_rad_tests` (
  `patient_wellness_record_id` int NOT NULL,
  `case_radiology_id` int NOT NULL,
  PRIMARY KEY (`patient_wellness_record_id`,`case_radiology_id`),
  KEY `IDX_4854763F223F0247` (`patient_wellness_record_id`),
  KEY `IDX_4854763F26A1E6F2` (`case_radiology_id`),
  CONSTRAINT `FK_4854763F223F0247` FOREIGN KEY (`patient_wellness_record_id`) REFERENCES `patient_wellness_records` (`id`) ON DELETE CASCADE,
  CONSTRAINT `FK_4854763F26A1E6F2` FOREIGN KEY (`case_radiology_id`) REFERENCES `case_rad_tests` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ------------------------------------------------------------------------------
-- Backfill records saved before this script. A record orders its tests the moment
-- it is saved OR edited, so the rows created on its case within a few seconds of
-- its created_at / updated_at are its own. (Rows a doctor added at another time
-- are correctly NOT claimed.) Records that only re-picked tests already on the
-- case created no rows to match; re-saving them (Edit -> Submit) attaches them.
-- ------------------------------------------------------------------------------
INSERT IGNORE INTO `patient_wellness_record_lab_tests` (`patient_wellness_record_id`, `case_laboratory_id`)
SELECT r.id, l.id
FROM `patient_wellness_records` r
JOIN `case_lab_tests` l ON l.case_id = r.case_id
WHERE r.lab_ordered = 1 AND r.case_id IS NOT NULL
  AND l.deleted_at IS NULL
  AND (ABS(TIMESTAMPDIFF(SECOND, l.created_at, r.created_at)) <= 10
    OR ABS(TIMESTAMPDIFF(SECOND, l.created_at, r.updated_at)) <= 10);

INSERT IGNORE INTO `patient_wellness_record_rad_tests` (`patient_wellness_record_id`, `case_radiology_id`)
SELECT r.id, x.id
FROM `patient_wellness_records` r
JOIN `case_rad_tests` x ON x.case_id = r.case_id
WHERE r.radiology_ordered = 1 AND r.case_id IS NOT NULL
  AND x.deleted_at IS NULL
  AND (ABS(TIMESTAMPDIFF(SECOND, x.created_at, r.created_at)) <= 10
    OR ABS(TIMESTAMPDIFF(SECOND, x.created_at, r.updated_at)) <= 10);

-- A package was clearly picked when every one of its tests is among the record's
-- own (packages with no tests are never inferred).
INSERT IGNORE INTO `patient_wellness_record_packages` (`patient_wellness_record_id`, `wellness_package_id`)
SELECT r.id, p.id
FROM `patient_wellness_records` r
JOIN `wellness_packages` p ON p.deleted_at IS NULL
WHERE (SELECT COUNT(*) FROM `wellness_package_lab_tests` pl WHERE pl.wellness_package_id = p.id)
    + (SELECT COUNT(*) FROM `wellness_package_radiology_tests` pr WHERE pr.wellness_package_id = p.id) > 0
  AND NOT EXISTS (
    SELECT 1 FROM `wellness_package_lab_tests` pl
    WHERE pl.wellness_package_id = p.id
      AND NOT EXISTS (
        SELECT 1 FROM `patient_wellness_record_lab_tests` rl
        JOIN `case_lab_tests` l ON l.id = rl.case_laboratory_id
        WHERE rl.patient_wellness_record_id = r.id AND l.lab_test_id = pl.lab_test_id))
  AND NOT EXISTS (
    SELECT 1 FROM `wellness_package_radiology_tests` pr
    WHERE pr.wellness_package_id = p.id
      AND NOT EXISTS (
        SELECT 1 FROM `patient_wellness_record_rad_tests` rr
        JOIN `case_rad_tests` x ON x.id = rr.case_radiology_id
        WHERE rr.patient_wellness_record_id = r.id AND x.test_id = pr.radiology_test_id));
