import { sql } from 'drizzle-orm'
import { check, integer, jsonb, pgTable, primaryKey, text, timestamp, uuid } from 'drizzle-orm/pg-core'
import { tenants } from './tenants'
import { users } from './users'

export const shellLayouts = pgTable(
  'shell_layouts',
  {
    tenantId: uuid('tenant_id').notNull().references(() => tenants.id, { onDelete: 'cascade' }),
    userId: uuid('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
    deviceClass: text('device_class').notNull(),
    payload: jsonb('payload').notNull(),
    version: integer('version').notNull().default(1),
    updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
  },
  (table) => ({
    pk: primaryKey({ columns: [table.tenantId, table.userId, table.deviceClass] }),
    deviceClassCheck: check('shell_layouts_device_class_check', sql`${table.deviceClass} IN ('desktop', 'mobile')`),
  }),
)

export type ShellLayoutRow = typeof shellLayouts.$inferSelect
export type NewShellLayout = typeof shellLayouts.$inferInsert
