import { relations } from 'drizzle-orm';
import { index, pgTable, primaryKey, timestamp, uuid, varchar } from 'drizzle-orm/pg-core';
import { users } from './auth';
import { moduleAccessLevelEnum } from './enums';

/**
 * Per-user module entitlements — which terminals an account may open.
 *
 * A missing row means NONE: a newly created account starts with nothing and an
 * administrator grants modules explicitly. Existing accounts were granted every
 * module by the migration that introduced this table, so nobody loses access.
 *
 * Administrators are not represented here at all; their access follows from the
 * role and is resolved in code (see fullModuleAccess). Storing rows for them
 * would create a second, divergent source of truth.
 */
export const userModuleAccess = pgTable(
  'user_module_access',
  {
    userId: uuid('user_id')
      .notNull()
      .references(() => users.id, { onDelete: 'cascade' }),
    module: varchar('module', { length: 32 }).notNull(),
    level: moduleAccessLevelEnum('level').notNull().default('NONE'),
    updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
  },
  (table) => [
    primaryKey({ columns: [table.userId, table.module] }),
    index('user_module_access_user_id_idx').on(table.userId),
  ],
);

export const userModuleAccessRelations = relations(userModuleAccess, ({ one }) => ({
  user: one(users, {
    fields: [userModuleAccess.userId],
    references: [users.id],
  }),
}));

export type UserModuleAccessRow = typeof userModuleAccess.$inferSelect;
