-- Snapshots dédiés aux enveloppes (strictement monétaires = valeur EUR uniquement)
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'));
CREATE INDEX idx_envelope_snapshot_lookup ON envelope_snapshot(envelope_id, date DESC);

-- Mise à jour de la table transaction :
-- Les enveloppes deviennent de vrais participants source/dest (plus de envelope_id de catégorie)
ALTER TABLE transaction
    DROP COLUMN envelope_id,
    ADD COLUMN envelope_source_id INTEGER REFERENCES envelope(id),
    ADD COLUMN envelope_dest_id   INTEGER REFERENCES envelope(id);

-- Remplacement de la contrainte CHECK pour couvrir account et envelope comme participants
ALTER TABLE transaction DROP CONSTRAINT chk_transaction_sides;

ALTER TABLE transaction ADD CONSTRAINT chk_transaction_sides CHECK (
    -- Côté source : au plus un parmi (account, envelope), les trois champs cohérents ou tous null
    (
        (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
    -- Côté dest : même logique
    (
        (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
    -- Au moins un côté doit exister
    (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)
);
