import { pgTable, text, timestamp } from "drizzle-orm/pg-core";
import { nostrIdentities } from "./nostr-identities";

// ── Access level type ─────────────────────────────────────────────────────────

export const RELAY_ACCESS_LEVELS = ["none", "read", "write"] as const;
export type RelayAccessLevel = (typeof RELAY_ACCESS_LEVELS)[number];

// ── relay_accounts ────────────────────────────────────────────────────────────
// One row per Nostr pubkey that has been explicitly registered with the relay.
// Absence = "none" (default deny). FK to nostr_identities ensures we always
// have a trust record alongside the relay record.

export const relayAccounts = pgTable("relay_accounts", {
  pubkey: text("pubkey")
    .primaryKey()
    .references(() => nostrIdentities.pubkey, { onDelete: "cascade" }),

  accessLevel: text("access_level")
    .$type<RelayAccessLevel>()
    .notNull()
    .default("none"),

  // "manual" = operator-granted regardless of trust tier
  // "auto-tier" = promoted automatically by TrustService
  grantedBy: text("granted_by").notNull().default("manual"),

  grantedAt: timestamp("granted_at", { withTimezone: true }).defaultNow().notNull(),

  // Set when access is revoked; null means currently active.
  revokedAt: timestamp("revoked_at", { withTimezone: true }),

  notes: text("notes"),
});

export type RelayAccount = typeof relayAccounts.$inferSelect;
