-- V16: Tables for backup tracking (BackupRecord + BackupConfig entities)

CREATE TABLE IF NOT EXISTS backup_records (
    id                      UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    date_creation           TIMESTAMP,
    date_modification       TIMESTAMP,
    cree_par                VARCHAR(255),
    modifie_par             VARCHAR(255),
    version                 BIGINT DEFAULT 0,
    actif                   BOOLEAN NOT NULL DEFAULT TRUE,
    name                    VARCHAR(200) NOT NULL,
    description             VARCHAR(500),
    type                    VARCHAR(50) NOT NULL,
    size_bytes              BIGINT,
    status                  VARCHAR(50) NOT NULL DEFAULT 'IN_PROGRESS',
    completed_at            TIMESTAMP,
    created_by              VARCHAR(200),
    includes_database       BOOLEAN NOT NULL DEFAULT TRUE,
    includes_files          BOOLEAN NOT NULL DEFAULT FALSE,
    includes_configuration  BOOLEAN NOT NULL DEFAULT TRUE,
    file_path               VARCHAR(500),
    error_message           TEXT
);

CREATE INDEX IF NOT EXISTS idx_backup_records_status     ON backup_records (status);
CREATE INDEX IF NOT EXISTS idx_backup_records_type       ON backup_records (type);
CREATE INDEX IF NOT EXISTS idx_backup_records_created_at ON backup_records (date_creation DESC);

-- -------------------------------------------------------

CREATE TABLE IF NOT EXISTS backup_config (
    id                      UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    date_creation           TIMESTAMP,
    date_modification       TIMESTAMP,
    cree_par                VARCHAR(255),
    modifie_par             VARCHAR(255),
    version                 BIGINT DEFAULT 0,
    actif                   BOOLEAN NOT NULL DEFAULT TRUE,
    auto_backup_enabled     BOOLEAN NOT NULL DEFAULT TRUE,
    frequency               VARCHAR(20) NOT NULL DEFAULT 'DAILY',
    retention_days          INTEGER NOT NULL DEFAULT 30,
    backup_time             VARCHAR(10) NOT NULL DEFAULT '02:00',
    include_database        BOOLEAN NOT NULL DEFAULT TRUE,
    include_files           BOOLEAN NOT NULL DEFAULT FALSE,
    include_configuration   BOOLEAN NOT NULL DEFAULT TRUE,
    backup_directory        VARCHAR(500)
);

-- Seed default config row (only if table is empty)
INSERT INTO backup_config (
    id, date_creation, date_modification, version, actif,
    auto_backup_enabled, frequency, retention_days, backup_time,
    include_database, include_files, include_configuration
)
SELECT
    gen_random_uuid(), NOW(), NOW(), 0, TRUE,
    TRUE, 'DAILY', 30, '02:00',
    TRUE, FALSE, TRUE
WHERE NOT EXISTS (SELECT 1 FROM backup_config);
