-- Migration: 006_add_maintenance_log
-- Author: Descomplicar®
-- Date: 2026-02-04
-- Description: Tabelas de controlo de migrations e log de manutenção

-- UP

-- Controlo de migrations
CREATE TABLE IF NOT EXISTS cr_migrations (
    id INT AUTO_INCREMENT PRIMARY KEY,
    migration_name VARCHAR(100) NOT NULL UNIQUE,
    applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    checksum VARCHAR(64),
    status ENUM('applied', 'rolled_back', 'failed') DEFAULT 'applied',
    execution_time_ms INT DEFAULT 0
);

-- Log de operações de manutenção
CREATE TABLE IF NOT EXISTS cr_maintenance_log (
    id INT AUTO_INCREMENT PRIMARY KEY,
    operation VARCHAR(50) NOT NULL,
    table_name VARCHAR(100),
    rows_affected INT DEFAULT 0,
    details JSON,
    executed_by VARCHAR(100) DEFAULT 'system',
    executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    status ENUM('success', 'failed', 'rolled_back') DEFAULT 'success',
    error_message TEXT
);

-- Índices
CREATE INDEX idx_migrations_status ON cr_migrations(status);
CREATE INDEX idx_maintenance_operation ON cr_maintenance_log(operation);
CREATE INDEX idx_maintenance_date ON cr_maintenance_log(executed_at);
CREATE INDEX idx_maintenance_status ON cr_maintenance_log(status);

-- DOWN
DROP TABLE IF EXISTS cr_maintenance_log;
DROP TABLE IF EXISTS cr_migrations;
