import { pgTable, text, timestamp, integer } from "drizzle-orm/pg-core";
import { createInsertSchema } from "drizzle-zod";
import { z } from "zod/v4";

// ── Trust tier labels ─────────────────────────────────────────────────────────
// Boundaries are env-var overridable via TrustService.

export const TRUST_TIERS = ["new", "established", "trusted", "elite"] as const;
export type TrustTier = (typeof TRUST_TIERS)[number];

// ── nostr_identities ──────────────────────────────────────────────────────────
// One row per Nostr pubkey (64-char lowercase hex). Trust score drives pricing
// decisions in the cost-routing layer (Task #27).

export const nostrIdentities = pgTable("nostr_identities", {
  pubkey: text("pubkey").primaryKey(),

  trustScore: integer("trust_score").notNull().default(0),
  tier: text("tier").$type<TrustTier>().notNull().default("new"),
  interactionCount: integer("interaction_count").notNull().default(0),

  // Rolling daily absorption budget (reset by TrustService on read)
  satsAbsorbedToday: integer("sats_absorbed_today").notNull().default(0),
  absorbedResetAt: timestamp("absorbed_reset_at", { withTimezone: true })
    .defaultNow()
    .notNull(),

  // Optional Lightning address (NIP-57 lud16 field, e.g. "user@domain.com").
  // Stored on first /identity/verify if the signed event includes a lud16 tag.
  // Used by ZapService to resolve LNURL-pay invoices for zap-out payments.
  lightningAddress: text("lightning_address"),

  lastSeen: timestamp("last_seen", { withTimezone: true }).defaultNow().notNull(),
  createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(),
  updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(),
});

export const insertNostrIdentitySchema = createInsertSchema(nostrIdentities).omit({
  createdAt: true,
  updatedAt: true,
});

export type NostrIdentity = typeof nostrIdentities.$inferSelect;
export type InsertNostrIdentity = z.infer<typeof insertNostrIdentitySchema>;
