-- Table de correspondance prod ↔ hors-prod
CREATE TABLE IF NOT EXISTS server_correspondance (
    id SERIAL PRIMARY KEY,
    prod_server_id INTEGER REFERENCES servers(id) ON DELETE CASCADE,
    nonprod_server_id INTEGER REFERENCES servers(id) ON DELETE CASCADE,
    environment_code VARCHAR(50),
    source VARCHAR(20) NOT NULL DEFAULT 'auto',
    note TEXT,
    created_by INTEGER REFERENCES users(id),
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW(),
    CONSTRAINT server_correspondance_source_check CHECK (source IN ('auto','manual','exception')),
    CONSTRAINT server_correspondance_uniq UNIQUE(prod_server_id, nonprod_server_id)
);
CREATE INDEX IF NOT EXISTS idx_corr_prod ON server_correspondance(prod_server_id);
CREATE INDEX IF NOT EXISTS idx_corr_nonprod ON server_correspondance(nonprod_server_id);

-- Table des validations post-patching
CREATE TABLE IF NOT EXISTS patch_validation (
    id SERIAL PRIMARY KEY,
    server_id INTEGER REFERENCES servers(id) ON DELETE CASCADE,
    campaign_id INTEGER,
    campaign_type VARCHAR(30),
    patch_date TIMESTAMP DEFAULT NOW(),
    status VARCHAR(20) NOT NULL DEFAULT 'en_attente',
    validated_by_contact_id INTEGER REFERENCES contacts(id),
    validated_by_name VARCHAR(200),
    validated_at TIMESTAMP,
    marked_by_user_id INTEGER REFERENCES users(id),
    forced_reason TEXT,
    notes TEXT,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW(),
    CONSTRAINT patch_validation_status_check CHECK (status IN ('en_attente','validated_ok','validated_ko','forced'))
);
CREATE INDEX IF NOT EXISTS idx_pv_server ON patch_validation(server_id);
CREATE INDEX IF NOT EXISTS idx_pv_campaign ON patch_validation(campaign_id, campaign_type);
CREATE INDEX IF NOT EXISTS idx_pv_status ON patch_validation(status);
CREATE INDEX IF NOT EXISTS idx_pv_patch_date ON patch_validation(patch_date DESC);

SELECT 'schema créé' as msg;
