import { pgTable, text, timestamp } from 'drizzle-orm/pg-core'

export const apiKeys = pgTable('api_keys', {
  id: text('id').primaryKey(),
  prefix: text('prefix').notNull().unique(),
  secretHash: text('secret_hash').notNull(),
  owner: text('owner').notNull(),
  scopes: text('scopes').notNull(),
  createdAt: timestamp('created_at', { withTimezone: true }).notNull(),
  lastUsedAt: timestamp('last_used_at', { withTimezone: true }),
  revokedAt: timestamp('revoked_at', { withTimezone: true }),
  expiresAt: timestamp('expires_at', { withTimezone: true }),
})

export const apiKeysCreationSql = () =>
  `CREATE TABLE IF NOT EXISTS api_keys (
    id text PRIMARY KEY,
    prefix text NOT NULL UNIQUE,
    secret_hash text NOT NULL,
    owner text NOT NULL,
    scopes text NOT NULL,
    created_at timestamptz NOT NULL,
    last_used_at timestamptz,
    revoked_at timestamptz,
    expires_at timestamptz
  )`

export const apiKeysSchema = {
  apiKeys,
}

export type ApiKeysSchema = typeof apiKeysSchema
