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

// ---------------------------------------------------------------------------
// Media schema — aligned to PRODUCTION as of 2026-05-19 baseline.
//
// Drift corrected at baseline:
//  - memories: vision_tags (text[]) and vision_embedding (vector(1536)) are
//    now modelled with Drizzle's native column types instead of being
//    "raw SQL only". The ivfflat index on the embedding is declared too.
// ---------------------------------------------------------------------------

// Processing states for background jobs
export type ProcessingStatus = "uploading" | "processing" | "ready" | "failed";

export const memories = pgTable(
  "memories",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    familyId: uuid("family_id").notNull(),
    childId: uuid("child_id"),
    title: text("title"),
    description: text("description"),
    takenAt: timestamp("taken_at", { withTimezone: true }),
    r2Key: text("r2_key").notNull(),
    r2ThumbnailKey: text("r2_thumbnail_key"),
    mimeType: text("mime_type"),
    sizeBytes: integer("size_bytes"),
    width: integer("width"),
    height: integer("height"),
    visionCaption: text("vision_caption"),
    visionTags: text("vision_tags").array(),
    visionEmbedding: vector("vision_embedding", { dimensions: 1536 }),
    isPrivate: boolean("is_private").default(false).notNull(),
    processingStatus: text("processing_status")
      .$type<ProcessingStatus>()
      .default("uploading")
      .notNull(),
    uploadedBy: uuid("uploaded_by"),
    createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(),
    updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(),
  },
  (table) => [
    index("memories_family_idx").on(table.familyId),
    index("memories_child_idx").on(table.childId),
    // ivfflat index for cosine similarity search over CLIP/vision embeddings.
    index("memories_embedding_idx")
      .using("ivfflat", table.visionEmbedding.op("vector_cosine_ops"))
      .with({ lists: 100 }),
  ]
);

export const attachments = pgTable(
  "attachments",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    familyId: uuid("family_id").notNull(),
    logEntryId: uuid("log_entry_id"),
    r2Key: text("r2_key").notNull(),
    r2ThumbnailKey: text("r2_thumbnail_key"),
    mimeType: text("mime_type"),
    sizeBytes: integer("size_bytes"),
    uploadedBy: uuid("uploaded_by"),
    createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(),
  },
  (table) => [index("attachments_family_idx").on(table.familyId)]
);

export type Memory = typeof memories.$inferSelect;
export type NewMemory = typeof memories.$inferInsert;
export type Attachment = typeof attachments.$inferSelect;
