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

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


export const notificationsItems = pgTable("notifications_items", {
    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, {
            onUpdate: "cascade",
            onDelete: "restrict",
        }),

    title: text("title").notNull(),
    message: text("message").notNull(),

    payload: jsonb("payload"),

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

    status: notificationStatusEnum("status").notNull().default("queued"),

    error: text("error"),

    createdAt: timestamp("created_at", { withTimezone: true })
        .notNull()
        .defaultNow(),

    sentAt: timestamp("sent_at", { withTimezone: true }),
    readAt: timestamp("read_at", { withTimezone: true }),
})

export type NotificationItem = typeof notificationsItems.$inferSelect
export type NewNotificationItem = typeof notificationsItems.$inferInsert
