-- Chat-Feature: Multi-Emoji-Reaktionen + Soft-Delete (Tombstone) für Room-Chat + DMs
-- Spiegelt die chat_message_likes-Struktur (20250712_chat_rooms_and_features),
-- erweitert um eine emoji-Spalte. PK (user_id, message_id) = eine Reaktion pro
-- User pro Message (neues Emoji ersetzt das alte — WhatsApp-Verhalten).

-- ─── Soft-Delete: deleted_at auf beiden Message-Typen ───────────────────────
ALTER TABLE "rebreak"."chat_messages"   ADD COLUMN "deleted_at" TIMESTAMP(3);
ALTER TABLE "rebreak"."direct_messages" ADD COLUMN "deleted_at" TIMESTAMP(3);

-- ─── Reaction-Tabelle: Room-Chat ────────────────────────────────────────────
CREATE TABLE "rebreak"."chat_message_reactions" (
    "user_id"    UUID NOT NULL,
    "message_id" UUID NOT NULL,
    "emoji"      TEXT NOT NULL,
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT "chat_message_reactions_pkey" PRIMARY KEY ("user_id","message_id")
);
CREATE INDEX "chat_message_reactions_message_id_idx" ON "rebreak"."chat_message_reactions"("message_id");
ALTER TABLE "rebreak"."chat_message_reactions"
    ADD CONSTRAINT "chat_message_reactions_message_id_fkey"
    FOREIGN KEY ("message_id") REFERENCES "rebreak"."chat_messages"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- ─── Reaction-Tabelle: Direct-Messages ──────────────────────────────────────
CREATE TABLE "rebreak"."direct_message_reactions" (
    "user_id"    UUID NOT NULL,
    "message_id" UUID NOT NULL,
    "emoji"      TEXT NOT NULL,
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT "direct_message_reactions_pkey" PRIMARY KEY ("user_id","message_id")
);
CREATE INDEX "direct_message_reactions_message_id_idx" ON "rebreak"."direct_message_reactions"("message_id");
ALTER TABLE "rebreak"."direct_message_reactions"
    ADD CONSTRAINT "direct_message_reactions_message_id_fkey"
    FOREIGN KEY ("message_id") REFERENCES "rebreak"."direct_messages"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- ─── Supabase Realtime ──────────────────────────────────────────────────────
-- Reaction-Tabellen zur Publication (chat_messages/direct_messages sind bereits
-- via 20260516_enable_chat_realtime drin; deren UPDATE-Events tragen das
-- deleted_at-Tombstone). Chat-Tabellen nutzen kein RLS (Prisma via Service-Role,
-- Scoping client-seitig via postgres_changes-Filter) — Reaction-Tabellen gleich.
ALTER PUBLICATION supabase_realtime ADD TABLE "rebreak"."chat_message_reactions";
ALTER PUBLICATION supabase_realtime ADD TABLE "rebreak"."direct_message_reactions";
