-- ==============================================================================
-- Automatic retry queue for ABDM care-context links.
--
-- Linking a report (discharge summary, prescription, ...) to the patient's PHR
-- runs as a side effect of a workflow step. When it fails - most often because
-- the companion ABDM app on :8000 is not running at that moment - nothing used
-- to retry it, so the record simply never reached the PHR. A failed link is now
-- queued here and retried automatically (Abha::autoLinkAndNotify records it,
-- AbhaLinkRetryRunner works the queue with exponential back-off).
--
-- One row per (case, HI type); a fresh failure re-arms an existing row.
-- ==============================================================================

CREATE TABLE IF NOT EXISTS `abha_link_retries` (
    `id`              INT UNSIGNED NOT NULL AUTO_INCREMENT,
    `case_id`         INT          NOT NULL,
    `hi_type`         VARCHAR(40)  NOT NULL,
    `attempts`        INT UNSIGNED NOT NULL DEFAULT 0,
    `last_error`      TEXT         NULL,
    `next_attempt_at` DATETIME     NOT NULL,
    `created_at`      DATETIME     NOT NULL,
    `resolved_at`     DATETIME     NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `uniq_case_hitype` (`case_id`, `hi_type`),
    KEY `idx_due` (`resolved_at`, `next_attempt_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
