ALTER TABLE payments
    ADD COLUMN IF NOT EXISTS txid VARCHAR(255) NULL AFTER reference,
    ADD COLUMN IF NOT EXISTS payment_network VARCHAR(64) NULL AFTER payment_currency,
    ADD COLUMN IF NOT EXISTS payment_asset VARCHAR(32) NULL AFTER payment_network,
    ADD COLUMN IF NOT EXISTS expected_amount_cad DECIMAL(18,8) NULL AFTER cad_value_at_payment,
    ADD COLUMN IF NOT EXISTS received_amount_cad DECIMAL(18,8) NULL AFTER expected_amount_cad,
    ADD COLUMN IF NOT EXISTS first_seen_at DATETIME NULL AFTER updated_at,
    ADD COLUMN IF NOT EXISTS last_checked_at DATETIME NULL AFTER first_seen_at,
    ADD COLUMN IF NOT EXISTS alert_24_sent_at DATETIME NULL AFTER last_checked_at,
    ADD COLUMN IF NOT EXISTS alert_48_sent_at DATETIME NULL AFTER alert_24_sent_at,
    ADD COLUMN IF NOT EXISTS success_after_alert_sent_at DATETIME NULL AFTER alert_48_sent_at,
    ADD COLUMN IF NOT EXISTS urgent_alert_sent_at DATETIME NULL AFTER success_after_alert_sent_at,
    ADD COLUMN IF NOT EXISTS overpayment_email_sent_at DATETIME NULL AFTER urgent_alert_sent_at,
    ADD COLUMN IF NOT EXISTS review_status VARCHAR(64) NOT NULL DEFAULT 'pending' AFTER payment_status,
    ADD COLUMN IF NOT EXISTS review_notes TEXT NULL AFTER notes;

ALTER TABLE invoices
    ADD COLUMN IF NOT EXISTS paid_via_method VARCHAR(64) NULL AFTER status,
    ADD COLUMN IF NOT EXISTS paid_via_asset VARCHAR(32) NULL AFTER paid_via_method,
    ADD COLUMN IF NOT EXISTS paid_via_network VARCHAR(64) NULL AFTER paid_via_asset;

CREATE TABLE IF NOT EXISTS payment_reconciliation_events (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    payment_id INT UNSIGNED NOT NULL,
    invoice_id INT UNSIGNED NOT NULL,
    event_type VARCHAR(64) NOT NULL,
    event_status VARCHAR(64) NOT NULL DEFAULT 'open',
    details LONGTEXT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    handled_at DATETIME NULL,
    handled_by VARCHAR(128) NULL,
    handled_notes TEXT NULL,
    KEY idx_pre_payment_id (payment_id),
    KEY idx_pre_invoice_id (invoice_id),
    KEY idx_pre_event_type (event_type),
    KEY idx_pre_event_status (event_status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS crypto_reconciliation_runs (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    run_mode VARCHAR(32) NOT NULL,
    started_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    finished_at DATETIME NULL,
    scanned_count INT NOT NULL DEFAULT 0,
    resolved_count INT NOT NULL DEFAULT 0,
    flagged_count INT NOT NULL DEFAULT 0,
    notes TEXT NULL,
    KEY idx_crr_run_mode (run_mode),
    KEY idx_crr_started_at (started_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
