-- version: 8
-- SP10: 277CA Payer-Rejected lane
-- Adds columns to capture the payer-side rejection state separate from
-- the existing 999-envelope rejection (file-level). A claim can be:
--   * REJECTED via 999 ACK AK5 R/E (envelope rejection, already covered
--     by rejected_at + rejection_reason from migration 0004)
--   * PAYER_REJECTED via 277CA STC A4/A6/A7 (claim-level rejection by
--     the payer after envelope acceptance)
-- We keep these distinct so operators can tell *why* a claim isn't
-- paid: was it our file (999), or was it the payer's adjudication?
--
-- Also creates two77ca_acks to persist parsed 277CA files (one row per
-- inbound 277CA file, with the per-claim status detail in raw_json).

ALTER TABLE claims ADD COLUMN payer_rejected_at TEXT;
ALTER TABLE claims ADD COLUMN payer_rejected_reason TEXT;
ALTER TABLE claims ADD COLUMN payer_rejected_status_code TEXT;
ALTER TABLE claims ADD COLUMN payer_rejected_by_277ca_id TEXT;

CREATE INDEX idx_claims_payer_rejected_at ON claims(payer_rejected_at);

CREATE TABLE two77ca_acks (
    id                INTEGER PRIMARY KEY AUTOINCREMENT,
    source_batch_id   TEXT NOT NULL REFERENCES batches(id) ON DELETE CASCADE,
    control_number    TEXT NOT NULL,
    accepted_count    INTEGER NOT NULL DEFAULT 0,
    rejected_count    INTEGER NOT NULL DEFAULT 0,
    paid_count        INTEGER NOT NULL DEFAULT 0,
    pended_count      INTEGER NOT NULL DEFAULT 0,
    parsed_at         TEXT NOT NULL,
    raw_json          TEXT
);

CREATE INDEX ix_two77ca_acks_source_batch_id ON two77ca_acks(source_batch_id);
CREATE INDEX ix_two77ca_acks_control_number ON two77ca_acks(control_number);

