-- Migration 0058 : Supprimer la colonne id_ecriture de la table immo (plus utilisée)
IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'immo' AND COLUMN_NAME = 'id_ecriture')
BEGIN
    -- Supprimer l index
    IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'nix_immo_id_ecriture' AND object_id = OBJECT_ID('immo'))
        EXEC('DROP INDEX nix_immo_id_ecriture ON immo')

    -- Supprimer la contrainte DEFAULT si elle existe
    DECLARE @constraintName NVARCHAR(200)
    SELECT @constraintName = d.name
    FROM sys.default_constraints d
    JOIN sys.columns c ON d.parent_object_id = c.object_id AND d.parent_column_id = c.column_id
    WHERE d.parent_object_id = OBJECT_ID('immo') AND c.name = 'id_ecriture'

    IF @constraintName IS NOT NULL
        EXEC('ALTER TABLE immo DROP CONSTRAINT ' + @constraintName)

    -- Supprimer la colonne
    EXEC('ALTER TABLE immo DROP COLUMN id_ecriture')
    PRINT 'Colonne id_ecriture supprimee de la table immo'
END
ELSE
BEGIN
    PRINT 'Colonne id_ecriture deja absente de la table immo - migration ignoree'
END
