import {
    pgTable,
    uuid,
    bigint,
    text,
    timestamp,
    boolean,
    uniqueIndex,
    index,
} from "drizzle-orm/pg-core"

import { tenants } from "./tenants"
import { authUsers } from "./auth_users"

export const communicationRooms = pgTable(
    "communication_rooms",
    {
        id: uuid("id").primaryKey().defaultRandom(),

        tenantId: bigint("tenant_id", { mode: "number" })
            .notNull()
            .references(() => tenants.id, { onDelete: "cascade" }),

        key: text("key").notNull(),
        name: text("name").notNull(),
        topic: text("topic"),
        type: text("type").notNull().default("room"),

        entityType: text("entity_type"),
        entityId: bigint("entity_id", { mode: "number" }),
        entityUuid: uuid("entity_uuid"),

        matrixRoomId: text("matrix_room_id"),
        matrixAlias: text("matrix_alias"),
        parentSpaceRoomId: text("parent_space_room_id"),

        archived: boolean("archived").notNull().default(false),

        createdAt: timestamp("created_at", { withTimezone: true })
            .notNull()
            .defaultNow(),
        updatedAt: timestamp("updated_at", { withTimezone: true }),
        createdBy: uuid("created_by").references(() => authUsers.id),
        updatedBy: uuid("updated_by").references(() => authUsers.id),
    },
    (table) => ({
        tenantKeyIdx: uniqueIndex("communication_rooms_tenant_key_idx")
            .on(table.tenantId, table.key),
        tenantIdx: index("communication_rooms_tenant_idx")
            .on(table.tenantId),
        entityIdx: index("communication_rooms_entity_idx")
            .on(table.tenantId, table.entityType, table.entityId, table.entityUuid),
    })
)

export type CommunicationRoom = typeof communicationRooms.$inferSelect
export type NewCommunicationRoom = typeof communicationRooms.$inferInsert
