import { pgTable, uuid, text, timestamp, boolean, jsonb } from 'drizzle-orm/pg-core';
import { organizations } from './organizations';
import { projects } from './projects';

export const apiKeys = pgTable('api_keys', {
  id: uuid('id').primaryKey().defaultRandom(),

  // Key data
  keyHash: text('key_hash').notNull().unique(),
  keyPrefix: text('key_prefix').notNull().default('bnt_'),

  // Key type: 'master' or 'project'
  keyType: text('key_type').notNull().$type<'master' | 'project'>(),

  // Foreign key relationships
  organizationId: uuid('organization_id').references(() => organizations.id, {
    onDelete: 'cascade',
  }),
  projectId: uuid('project_id').references(() => projects.id, { onDelete: 'cascade' }),

  // Permissions (for future use)
  scopes: jsonb('scopes').$type<string[]>().notNull().default(['generate']),

  // Lifecycle
  createdAt: timestamp('created_at').notNull().defaultNow(),
  expiresAt: timestamp('expires_at'), // NULL for master keys, NOW() + 90 days for project
  lastUsedAt: timestamp('last_used_at'),
  isActive: boolean('is_active').notNull().default(true),

  // Metadata
  name: text('name'), // Optional friendly name
  createdBy: uuid('created_by'), // Which key created this key (for audit)
});

export type ApiKey = typeof apiKeys.$inferSelect;
export type NewApiKey = typeof apiKeys.$inferInsert;
