CREATE TABLE IF NOT EXISTS "communication_rooms" (
    "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
    "tenant_id" bigint NOT NULL,
    "key" text NOT NULL,
    "name" text NOT NULL,
    "topic" text,
    "type" text DEFAULT 'room' NOT NULL,
    "entity_type" text,
    "entity_id" bigint,
    "entity_uuid" uuid,
    "matrix_room_id" text,
    "matrix_alias" text,
    "parent_space_room_id" text,
    "archived" boolean DEFAULT false NOT NULL,
    "created_at" timestamp with time zone DEFAULT now() NOT NULL,
    "updated_at" timestamp with time zone,
    "created_by" uuid,
    "updated_by" uuid
);

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM pg_constraint WHERE conname = 'communication_rooms_tenant_id_tenants_id_fk'
    ) THEN
        ALTER TABLE "communication_rooms"
            ADD CONSTRAINT "communication_rooms_tenant_id_tenants_id_fk"
            FOREIGN KEY ("tenant_id") REFERENCES "public"."tenants"("id")
            ON DELETE cascade ON UPDATE no action;
    END IF;

    IF NOT EXISTS (
        SELECT 1 FROM pg_constraint WHERE conname = 'communication_rooms_created_by_auth_users_id_fk'
    ) THEN
        ALTER TABLE "communication_rooms"
            ADD CONSTRAINT "communication_rooms_created_by_auth_users_id_fk"
            FOREIGN KEY ("created_by") REFERENCES "public"."auth_users"("id")
            ON DELETE no action ON UPDATE no action;
    END IF;

    IF NOT EXISTS (
        SELECT 1 FROM pg_constraint WHERE conname = 'communication_rooms_updated_by_auth_users_id_fk'
    ) THEN
        ALTER TABLE "communication_rooms"
            ADD CONSTRAINT "communication_rooms_updated_by_auth_users_id_fk"
            FOREIGN KEY ("updated_by") REFERENCES "public"."auth_users"("id")
            ON DELETE no action ON UPDATE no action;
    END IF;
END $$;

CREATE UNIQUE INDEX IF NOT EXISTS "communication_rooms_tenant_key_idx"
    ON "communication_rooms" USING btree ("tenant_id", "key");

CREATE INDEX IF NOT EXISTS "communication_rooms_tenant_idx"
    ON "communication_rooms" USING btree ("tenant_id");

CREATE INDEX IF NOT EXISTS "communication_rooms_entity_idx"
    ON "communication_rooms" USING btree ("tenant_id", "entity_type", "entity_id", "entity_uuid");
