import {
  pgTable,
  text,
  timestamp,
  uuid,
  varchar,
  integer,
  numeric,
  index,
} from "drizzle-orm/pg-core";

// ---------------------------------------------------------------------------
// AI schema — aligned to PRODUCTION as of 2026-05-19 baseline.
// Tables: chat_sessions, chat_messages, ai_usage
// (legacy migrations 0004_chat_sessions, 0013_ai_usage).
// ---------------------------------------------------------------------------

export const chatSessions = pgTable("chat_sessions", {
  id: uuid("id").primaryKey().defaultRandom(),
  childId: uuid("child_id").notNull(),
  title: varchar("title", { length: 255 }).default("New conversation").notNull(),
  createdAt: timestamp("created_at", { withTimezone: true }).defaultNow(),
  updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow(),
});

export const chatMessages = pgTable("chat_messages", {
  id: uuid("id").primaryKey().defaultRandom(),
  sessionId: uuid("session_id").notNull(),
  role: varchar("role", { length: 20 }).notNull(),
  content: text("content").notNull(),
  createdAt: timestamp("created_at", { withTimezone: true }).defaultNow(),
});

// Token + cost accounting for the LiteLLM-gateway AI calls.
// cost_estimate_paise stores cost in Indian paise (1 INR = 100 paise) so
// fractional model costs stay exact without float drift.
export const aiUsage = pgTable(
  "ai_usage",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    familyId: uuid("family_id"),
    userId: uuid("user_id"),
    intent: text("intent"),
    modelUsed: text("model_used"),
    promptTokens: integer("prompt_tokens"),
    completionTokens: integer("completion_tokens"),
    totalTokens: integer("total_tokens"),
    costEstimatePaise: numeric("cost_estimate_paise", { precision: 10, scale: 4 }),
    durationMs: integer("duration_ms"),
    createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(),
  },
  (table) => [
    index("ai_usage_created_idx").on(table.createdAt),
    index("ai_usage_family_idx").on(table.familyId),
  ]
);

export type ChatSession = typeof chatSessions.$inferSelect;
export type ChatMessage = typeof chatMessages.$inferSelect;
export type AiUsage = typeof aiUsage.$inferSelect;
