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

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

export const notificationsPreferencesDefaults = pgTable(
    "notifications_preferences_defaults",
    {
        id: uuid("id").primaryKey().defaultRandom(),

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

        eventKey: text("event_key")
            .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) => ({
        uniqueDefaults: uniqueIndex(
            "notifications_preferences_defau_tenant_id_event_key_channel_key",
        ).on(table.tenantId, table.eventKey, table.channel),
    }),
)

export type NotificationPreferenceDefault =
    typeof notificationsPreferencesDefaults.$inferSelect
export type NewNotificationPreferenceDefault =
    typeof notificationsPreferencesDefaults.$inferInsert
