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

// ── nostr_trust_vouches ───────────────────────────────────────────────────────
// One row per elite co-signing event. Two uniqueness guards prevent trust fraud:
//   1. (voucher_pubkey, vouchee_pubkey) — each elite may vouch for a given target
//      only once; subsequent calls return existing state without additional boost.
//   2. event_id — a specific signed event cannot be replayed against different
//      target pubkeys.

export const nostrTrustVouches = pgTable(
  "nostr_trust_vouches",
  {
    id: text("id").primaryKey(),

    voucherPubkey: text("voucher_pubkey")
      .notNull()
      .references(() => nostrIdentities.pubkey),

    voucheePubkey: text("vouchee_pubkey").notNull(),

    // NIP-01 event id (sha256 of serialised event) — prevents replay of the same
    // signed event against a different voucheePubkey.
    eventId: text("event_id").notNull().unique(),

    vouchEventJson: text("vouch_event_json").notNull(),

    trustBoost: integer("trust_boost").notNull().default(20),

    createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(),
  },
  (table) => [
    // Enforce one vouch per (voucher, vouchee) pair — idempotency guard.
    uniqueIndex("uq_nostr_trust_vouches_pair").on(table.voucherPubkey, table.voucheePubkey),
  ],
);

export type NostrTrustVouch = typeof nostrTrustVouches.$inferSelect;
