-- Recréation de la table envelope
CREATE TABLE envelope (
    id             SERIAL PRIMARY KEY,
    account_id     INTEGER NOT NULL REFERENCES account(id) ON DELETE CASCADE,
    nom            TEXT NOT NULL,
    objectif       TEXT,
    montant_alloue NUMERIC(24, 8) NOT NULL DEFAULT 0
);

-- Remigration des sous-comptes vers envelope
INSERT INTO envelope (account_id, nom, objectif, montant_alloue)
SELECT master_account_id, nom, objectif, COALESCE(montant_alloue, 0)
FROM account WHERE master_account_id IS NOT NULL;

-- Suppression des sous-comptes de account
DELETE FROM account WHERE master_account_id IS NOT NULL;

ALTER TABLE account
    DROP COLUMN master_account_id,
    DROP COLUMN objectif,
    DROP COLUMN montant_alloue;

-- Restauration envelope_snapshot
CREATE TABLE envelope_snapshot (
    date        DATE    NOT NULL,
    envelope_id INTEGER NOT NULL REFERENCES envelope(id) ON DELETE CASCADE,
    valeur      NUMERIC(24, 8) NOT NULL,
    PRIMARY KEY (date, envelope_id)
);
SELECT create_hypertable('envelope_snapshot', by_range('date'));

-- Restauration transaction avec envelope_source/dest
ALTER TABLE transaction
    DROP CONSTRAINT chk_transaction_sides,
    ADD COLUMN envelope_source_id INTEGER REFERENCES envelope(id),
    ADD COLUMN envelope_dest_id   INTEGER REFERENCES envelope(id);

ALTER TABLE transaction ADD CONSTRAINT chk_transaction_sides CHECK (
    (account_source_id IS NOT NULL AND envelope_source_id IS NULL
     OR account_source_id IS NULL AND envelope_source_id IS NOT NULL
     OR account_source_id IS NULL AND envelope_source_id IS NULL)
    AND
    (((account_source_id IS NOT NULL OR envelope_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 envelope_source_id IS NULL
         AND instrument_source_id IS NULL AND quantite_source IS NULL))
    AND
    (account_dest_id IS NOT NULL AND envelope_dest_id IS NULL
     OR account_dest_id IS NULL AND envelope_dest_id IS NOT NULL
     OR account_dest_id IS NULL AND envelope_dest_id IS NULL)
    AND
    (((account_dest_id IS NOT NULL OR envelope_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 envelope_dest_id IS NULL
         AND instrument_dest_id IS NULL AND quantite_dest IS NULL))
    AND
    (account_source_id IS NOT NULL OR envelope_source_id IS NOT NULL
     OR account_dest_id IS NOT NULL OR envelope_dest_id IS NOT NULL)
);
