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

import { tenants } from "./tenants"
import { authUsers } from "./auth_users"
import { notificationsEventTypes } from "./notifications_event_types"
import {notificationChannelEnum} from "./enums";

export const notificationsPreferences = pgTable(
    "notifications_preferences",
    {
        id: uuid("id").primaryKey().defaultRandom(),

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

        userId: uuid("user_id")
            .notNull()
            .references(() => authUsers.id, {
                onDelete: "cascade",
                onUpdate: "cascade",
            }),

        eventType: text("event_type")
            .notNull()
            .references(() => notificationsEventTypes.eventKey, {
                onDelete: "restrict",
                onUpdate: "cascade",
            }),

        channel: notificationChannelEnum("channel").notNull(),

        enabled: boolean("enabled").notNull().default(true),

        createdAt: timestamp("created_at", { withTimezone: true })
            .notNull()
            .defaultNow(),
    },
    (table) => ({
        uniquePrefs: uniqueIndex(
            "notifications_preferences_tenant_id_user_id_event_type_chan_key",
        ).on(table.tenantId, table.userId, table.eventType, table.channel),
    }),
)

export type NotificationPreference =
    typeof notificationsPreferences.$inferSelect
export type NewNotificationPreference =
    typeof notificationsPreferences.$inferInsert
