import { pgTable, text, timestamp, integer, real, boolean } from "drizzle-orm/pg-core";
import { createInsertSchema } from "drizzle-zod";
import { z } from "zod/v4";
import { nostrIdentities } from "./nostr-identities";

export const JOB_STATES = [
  "awaiting_eval_payment",
  "evaluating",
  "rejected",
  "awaiting_work_payment",
  "executing",
  "complete",
  "failed",
] as const;

export type JobState = (typeof JOB_STATES)[number];

export const jobs = pgTable("jobs", {
  id: text("id").primaryKey(),
  request: text("request").notNull(),
  state: text("state").$type<JobState>().notNull().default("awaiting_eval_payment"),
  evalInvoiceId: text("eval_invoice_id"),
  workInvoiceId: text("work_invoice_id"),
  evalAmountSats: integer("eval_amount_sats").notNull(),
  workAmountSats: integer("work_amount_sats"),
  rejectionReason: text("rejection_reason"),
  result: text("result"),
  errorMessage: text("error_message"),

  // ── Cost-based pricing (set when work invoice is created) ───────────────
  estimatedCostUsd: real("estimated_cost_usd"),
  marginPct: real("margin_pct"),
  btcPriceUsd: real("btc_price_usd"),

  // ── Actual token usage (set after work executes) ────────────────────────
  actualInputTokens: integer("actual_input_tokens"),
  actualOutputTokens: integer("actual_output_tokens"),
  actualCostUsd: real("actual_cost_usd"),

  // Optional Nostr identity bound at job creation (FK → nostr_identities.pubkey)
  nostrPubkey: text("nostr_pubkey").references(() => nostrIdentities.pubkey),

  // ── Free-tier routing (Task #27) ─────────────────────────────────────────
  // freeTier=true: Timmy absorbed the work cost from the generosity pool.
  // absorbedSats: how many sats Timmy absorbed (0 for fully-paid jobs).
  freeTier: boolean("free_tier").notNull().default(false),
  absorbedSats: integer("absorbed_sats"),

  // ── Post-work honest accounting & refund ─────────────────────────────────
  actualAmountSats: integer("actual_amount_sats"),
  refundAmountSats: integer("refund_amount_sats"),
  refundState: text("refund_state").$type<"not_applicable" | "pending" | "paid">(),
  refundPaymentHash: text("refund_payment_hash"),

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

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

export type Job = typeof jobs.$inferSelect;
export type InsertJob = z.infer<typeof insertJobSchema>;
