-- Les enveloppes deviennent des comptes avec master_account_id
-- Un sous-compte hérite du type et de la devise de son compte maître
ALTER TABLE account
    ADD COLUMN master_account_id INTEGER REFERENCES account(id) ON DELETE CASCADE,
    ADD COLUMN objectif           TEXT,
    ADD COLUMN montant_alloue     NUMERIC(24, 8);

-- Migration des enveloppes existantes vers account
INSERT INTO account (nom, type, devise_reference, master_account_id, objectif, montant_alloue)
SELECT e.nom, a.type, a.devise_reference, e.account_id, e.objectif, e.montant_alloue
FROM envelope e
JOIN account a ON a.id = e.account_id;

-- Suppression des champs envelope_source/dest ajoutés en 000004
-- (les enveloppes étant désormais des comptes, account_source_id suffit)
ALTER TABLE transaction
    DROP CONSTRAINT chk_transaction_sides,
    DROP COLUMN envelope_source_id,
    DROP COLUMN envelope_dest_id;

ALTER TABLE transaction ADD CONSTRAINT chk_transaction_sides CHECK (
    (
        account_source_id    IS NOT NULL AND
        instrument_source_id IS NOT NULL AND
        quantite_source      IS NOT NULL
        OR
        account_source_id    IS NULL AND
        instrument_source_id IS NULL AND
        quantite_source      IS NULL
    )
    AND
    (
        account_dest_id    IS NOT NULL AND
        instrument_dest_id IS NOT NULL AND
        quantite_dest      IS NOT NULL
        OR
        account_dest_id    IS NULL AND
        instrument_dest_id IS NULL AND
        quantite_dest      IS NULL
    )
    AND
    (account_source_id IS NOT NULL OR account_dest_id IS NOT NULL)
);

-- Suppression de la FK envelope_id dans recurring_rule avant de dropper envelope
ALTER TABLE recurring_rule DROP COLUMN envelope_id;

-- Suppression des tables envelope devenues inutiles
DROP TABLE IF EXISTS envelope_snapshot;
DROP TABLE IF EXISTS envelope;
