-- 019_mixer_channels.sql
-- Mixer-kanaler for delt lydmixer-tilstand mellom deltakere i LiveKit-rom.
--
-- Migrert fra SpacetimeDB til PostgreSQL som del av Fase M2 (oppgave 22.2).
-- Portvokteren sender endringer via WebSocket til tilkoblede klienter.

BEGIN;

-- =============================================================================
-- mixer_channels: Delt mixer-tilstand per deltaker per rom.
-- =============================================================================

CREATE TABLE IF NOT EXISTS mixer_channels (
    room_id        TEXT NOT NULL,
    target_user_id TEXT NOT NULL,
    gain           DOUBLE PRECISION NOT NULL DEFAULT 1.0,
    is_muted       BOOLEAN NOT NULL DEFAULT false,
    active_effects TEXT NOT NULL DEFAULT '{}',  -- JSON-streng med effekttilstand
    role           TEXT NOT NULL DEFAULT 'editor',
    updated_by     TEXT NOT NULL DEFAULT '',
    updated_at     TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY (room_id, target_user_id)
);

-- =============================================================================
-- notify_mixer_channel_change: NOTIFY ved endringer i mixer_channels.
-- =============================================================================

CREATE OR REPLACE FUNCTION notify_mixer_channel_change()
RETURNS trigger AS $$
DECLARE
  payload json;
  target_row mixer_channels%ROWTYPE;
BEGIN
  IF TG_OP = 'DELETE' THEN
    target_row := OLD;
  ELSE
    target_row := NEW;
  END IF;

  payload := json_build_object(
    'op', TG_OP,
    'room_id', target_row.room_id,
    'target_user_id', target_row.target_user_id
  );

  PERFORM pg_notify('mixer_channel_changed', payload::text);
  RETURN target_row;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER mixer_channels_notify
  AFTER INSERT OR UPDATE OR DELETE ON mixer_channels
  FOR EACH ROW EXECUTE FUNCTION notify_mixer_channel_change();

COMMIT;
