CREATE TABLE IF NOT EXISTS ledger_entries ( id INT AUTO_INCREMENT PRIMARY KEY, tenant_id INT NOT NULL, participant_id INT NOT NULL, type VARCHAR(30) NOT NULL, amount_cents INT NOT NULL, marks_count INT NULL, unit_price_cents INT NULL, booked_at DATETIME NOT NULL, source VARCHAR(40) NOT NULL DEFAULT 'legacy', note VARCHAR(1000) NULL, created_by_user_id INT NULL, import_batch_id INT NULL, legacy_table VARCHAR(100) NULL, legacy_id INT NULL, voided_at DATETIME NULL, reversal_of_entry_id INT NULL, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, UNIQUE KEY uq_ledger_entries_tenant_legacy (tenant_id, legacy_table, legacy_id), KEY idx_ledger_entries_tenant_booked_at (tenant_id, booked_at), KEY idx_ledger_entries_participant_booked_at (participant_id, booked_at), KEY idx_ledger_entries_tenant_type (tenant_id, type), KEY idx_ledger_entries_reversal (reversal_of_entry_id), KEY idx_ledger_entries_created_by_user (created_by_user_id), CONSTRAINT fk_ledger_entries_tenant FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE, CONSTRAINT fk_ledger_entries_participant FOREIGN KEY (participant_id) REFERENCES participants(id) ON DELETE CASCADE, CONSTRAINT fk_ledger_entries_created_by_user FOREIGN KEY (created_by_user_id) REFERENCES users(id) ON DELETE SET NULL, CONSTRAINT fk_ledger_entries_reversal FOREIGN KEY (reversal_of_entry_id) REFERENCES ledger_entries(id) ON DELETE SET NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;