-- Migrazione per aggiungere supporto completo allo scheduling con storico esecuzioni

-- 1. Aggiungi colonne per override database nella tabella ProfileSchedules
ALTER TABLE ProfileSchedules ADD COLUMN SourceDatabaseOverride TEXT;
ALTER TABLE ProfileSchedules ADD COLUMN DestinationDatabaseOverride TEXT;

-- 2. Crea tabella per lo storico delle esecuzioni
CREATE TABLE IF NOT EXISTS ScheduleExecutionHistories (
    Id INTEGER PRIMARY KEY AUTOINCREMENT,
    ScheduleId INTEGER NOT NULL,
    ProfileId INTEGER NOT NULL,
    ProfileName TEXT NOT NULL,
    StartTime DATETIME NOT NULL,
    EndTime DATETIME,
    Status TEXT NOT NULL,
    Message TEXT,
    RecordsProcessed INTEGER DEFAULT 0,
    RecordsWithErrors INTEGER,
    ErrorDetails TEXT,
    TriggerType TEXT NOT NULL,
    TriggeredBy TEXT,
    SourceType TEXT,
    DestinationType TEXT,
    SourceInfo TEXT,
    DestinationInfo TEXT,
    AdditionalInfo TEXT,
    CreatedAt DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (ScheduleId) REFERENCES ProfileSchedules (Id) ON DELETE CASCADE
);

-- 3. Crea indici per ottimizzare le query
CREATE INDEX IF NOT EXISTS IDX_ScheduleExecutionHistories_ScheduleId ON ScheduleExecutionHistories (ScheduleId);
CREATE INDEX IF NOT EXISTS IDX_ScheduleExecutionHistories_ProfileId ON ScheduleExecutionHistories (ProfileId);
CREATE INDEX IF NOT EXISTS IDX_ScheduleExecutionHistories_Status ON ScheduleExecutionHistories (Status);
CREATE INDEX IF NOT EXISTS IDX_ScheduleExecutionHistories_StartTime ON ScheduleExecutionHistories (StartTime);
CREATE INDEX IF NOT EXISTS IDX_ScheduleExecutionHistories_TriggerType ON ScheduleExecutionHistories (TriggerType);

-- 4. Aggiorna eventuali schedulazioni esistenti per impostare NextExecutionTime se null
-- Questo è utile se ci sono già delle schedulazioni nel database
UPDATE ProfileSchedules 
SET NextExecutionTime = datetime('now', '+1 hour')
WHERE NextExecutionTime IS NULL AND IsActive = 1 AND IsEnabled = 1;

PRAGMA foreign_keys = ON;