import { pgTable, integer, text, timestamp } from 'drizzle-orm/pg-core';
import { users } from '../auth/schema';

// Officer Vault server-side state (see VAULT_AUTH_SPEC.md). The device never holds a Vaultwarden token;
// the platform brokers it, stores it here tied to the owner account, and injects it on proxied /api/vault
// requests. All secret columns are AES-256-GCM encrypted at rest (see ../crypto.ts).

// The brokered Vaultwarden token set. One row per owner account (single active vault session). Dropped on
// platform logout / distress / panic.
export const vaultTokens = pgTable('vault_tokens', {
  userId: integer('user_id')
    .primaryKey()
    .references(() => users.id, { onDelete: 'cascade' }),
  accessToken: text('access_token').notNull(), // encrypted
  refreshToken: text('refresh_token').notNull(), // encrypted
  expiresAt: timestamp('expires_at', { withTimezone: true }),
  deviceIdentifier: text('device_identifier'), // plaintext; the last device that brokered a login
  clientId: text('client_id'), // plaintext; the connect/token client_id, needed to refresh
  updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
});

// The platform-held "protector key" for the Officer-app unlock path: it unwraps the on-device wrapped user
// key, so a valid platform session opens the vault without the master password. Persists across normal
// logout (frictionless re-login); wiped on distress/panic (forces a one-time master-password re-setup).
// The zero-knowledge OffVault path never writes here (its protector stays in the Secure Enclave).
export const vaultUnlockKeys = pgTable('vault_unlock_keys', {
  userId: integer('user_id')
    .primaryKey()
    .references(() => users.id, { onDelete: 'cascade' }),
  wrappedKey: text('wrapped_key').notNull(), // encrypted (the protector key)
  updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
});
