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

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

export const notificationPushSubscriptions = pgTable(
    "notification_push_subscriptions",
    {
        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" }),

        endpoint: text("endpoint").notNull(),
        p256dh: text("p256dh").notNull(),
        auth: text("auth").notNull(),
        userAgent: text("user_agent"),
        deviceLabel: text("device_label"),
        meta: jsonb("meta"),

        createdAt: timestamp("created_at", { withTimezone: true })
            .notNull()
            .defaultNow(),
        lastSeenAt: timestamp("last_seen_at", { withTimezone: true })
            .notNull()
            .defaultNow(),
        disabledAt: timestamp("disabled_at", { withTimezone: true }),
    },
    (table) => ({
        uniqueEndpoint: uniqueIndex("notification_push_subscriptions_endpoint_key").on(table.endpoint),
    }),
)

export type NotificationPushSubscription =
    typeof notificationPushSubscriptions.$inferSelect
export type NewNotificationPushSubscription =
    typeof notificationPushSubscriptions.$inferInsert
