-- 016_message_placements.sql
-- Plasseringsrelasjon: sporer hvor meldinger vises på tvers av kontekster.
-- En melding (node) kan ha plasseringer i flere kontekster samtidig
-- (chat, kanban, storyboard, kalender, notes).
--
-- Ref: docs/features/universell_overfoering.md § 2

BEGIN;

CREATE TABLE message_placements (
    id           UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    message_id   UUID NOT NULL REFERENCES nodes(id) ON DELETE CASCADE,
    context_type TEXT NOT NULL,  -- 'chat', 'kanban', 'storyboard', 'calendar', 'notes'
    context_id   UUID NOT NULL,  -- channel_id, board_id, episode_id, calendar_id, note_id
    entered_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
    position     JSONB,          -- kontekst-spesifikk posisjon (se § 2.2)
    UNIQUE (message_id, context_type, context_id)
);

-- Oppslag: alle meldinger i en gitt kontekst, sortert etter ankomst
CREATE INDEX idx_placements_context ON message_placements(context_type, context_id, entered_at);

-- Oppslag: alle plasseringer for en gitt melding
CREATE INDEX idx_placements_message ON message_placements(message_id);

COMMENT ON TABLE message_placements IS 'Plasseringsrelasjon — sporer hvor meldinger vises. Ref: docs/features/universell_overfoering.md § 2';
COMMENT ON COLUMN message_placements.message_id IS 'Meldingens node-id (node_kind = melding)';
COMMENT ON COLUMN message_placements.context_type IS 'Konteksttype: chat, kanban, storyboard, calendar, notes';
COMMENT ON COLUMN message_placements.context_id IS 'ID til kontekstnoden (kanal, brett, episode, etc.)';
COMMENT ON COLUMN message_placements.entered_at IS 'Når meldingen ankom denne konteksten (ikke created_at)';
COMMENT ON COLUMN message_placements.position IS 'Kontekst-spesifikk posisjon som JSONB. null=sortert etter entered_at (chat). {x,y}=canvas (storyboard). {column_id,position}=kanban. {date,all_day}=kalender. {position}=notes.';

COMMIT;
