SET NAMES utf8mb4;

ALTER TABLE credit_transactions
    ADD COLUMN settlement_status ENUM('settled', 'pending', 'released') NOT NULL DEFAULT 'settled' AFTER movement_type,
    ADD COLUMN source_type VARCHAR(100) NULL AFTER reason,
    ADD COLUMN source_id BIGINT UNSIGNED NULL AFTER source_type,
    ADD COLUMN metadata_json JSON NULL AFTER source_id,
    ADD COLUMN reversed_transaction_id BIGINT UNSIGNED NULL AFTER metadata_json,
    ADD INDEX idx_credit_transactions_order_settlement (order_id, settlement_status),
    ADD INDEX idx_credit_transactions_account_settlement (account_id, settlement_status),
    ADD INDEX idx_credit_transactions_source (source_type, source_id),
    ADD CONSTRAINT fk_credit_transactions_reversed FOREIGN KEY (reversed_transaction_id) REFERENCES credit_transactions(id);

CREATE TABLE audit_logs (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    actor_user_id BIGINT UNSIGNED NULL,
    impersonator_user_id BIGINT UNSIGNED NULL,
    module_code VARCHAR(100) NOT NULL,
    action_code VARCHAR(120) NOT NULL,
    entity_type VARCHAR(100) NOT NULL,
    entity_id BIGINT UNSIGNED NULL,
    network_id BIGINT UNSIGNED NULL,
    shop_id BIGINT UNSIGNED NULL,
    context_json JSON NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_audit_logs_actor (actor_user_id),
    INDEX idx_audit_logs_module_action (module_code, action_code),
    INDEX idx_audit_logs_entity (entity_type, entity_id),
    INDEX idx_audit_logs_scope (network_id, shop_id),
    INDEX idx_audit_logs_created_at (created_at),
    CONSTRAINT fk_audit_logs_actor FOREIGN KEY (actor_user_id) REFERENCES users(id),
    CONSTRAINT fk_audit_logs_impersonator FOREIGN KEY (impersonator_user_id) REFERENCES users(id),
    CONSTRAINT fk_audit_logs_network FOREIGN KEY (network_id) REFERENCES networks(id),
    CONSTRAINT fk_audit_logs_shop FOREIGN KEY (shop_id) REFERENCES shops(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
