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

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

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

        localDeviceId: text("local_device_id").notNull(),
        centralDeviceId: text("central_device_id").notNull(),
        platform: text("platform").notNull(),
        providerTokenPreview: text("provider_token_preview"),
        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) => ({
        uniqueUserDevice: uniqueIndex("notification_mobile_push_devices_user_device_key")
            .on(table.tenantId, table.userId, table.localDeviceId),
        uniqueCentralDevice: uniqueIndex("notification_mobile_push_devices_central_device_key")
            .on(table.centralDeviceId),
    }),
)

export type NotificationMobilePushDevice =
    typeof notificationMobilePushDevices.$inferSelect
export type NewNotificationMobilePushDevice =
    typeof notificationMobilePushDevices.$inferInsert
