import { pgTable, text, timestamp, uniqueIndex, index, uuid, boolean, jsonb } from "drizzle-orm/pg-core";
import { subscriptions } from "./subscription";
import { watchlistType, exposureSource, exposureSeverity } from "./enums";

export const watchlistItems = pgTable("watchlist_items", {
  id: uuid("id").defaultRandom().primaryKey(),
  subscriptionId: uuid("subscription_id").notNull().references(() => subscriptions.id, { onDelete: "cascade" }),
  type: watchlistType("type").notNull(),
  value: text("value").notNull(),
  hash: text("hash").notNull(),
  isActive: boolean("is_active").default(true).notNull(),
  createdAt: timestamp("created_at", { withTimezone: true, mode: "date" }).defaultNow().notNull(),
  updatedAt: timestamp("updated_at", { withTimezone: true, mode: "date" }).defaultNow().notNull().$onUpdate(() => new Date()),
}, (table) => ({
  subTypeHashUnique: uniqueIndex("watchlist_items_sub_type_hash_unique").on(table.subscriptionId, table.type, table.hash),
  subscriptionIdIdx: index("watchlist_items_subscription_id_idx").on(table.subscriptionId),
  typeIdx: index("watchlist_items_type_idx").on(table.type),
  hashIdx: index("watchlist_items_hash_idx").on(table.hash),
}));

export const exposures = pgTable("exposures", {
  id: uuid("id").defaultRandom().primaryKey(),
  subscriptionId: uuid("subscription_id").notNull().references(() => subscriptions.id, { onDelete: "cascade" }),
  watchlistItemId: uuid("watchlist_item_id").references(() => watchlistItems.id),
  source: exposureSource("source").notNull(),
  dataType: watchlistType("data_type").notNull(),
  identifier: text("identifier").notNull(),
  identifierHash: text("identifier_hash").notNull(),
  severity: exposureSeverity("severity").default("info").notNull(),
  metadata: jsonb("metadata"),
  isFirstTime: boolean("is_first_time").default(false).notNull(),
  detectedAt: timestamp("detected_at", { withTimezone: true, mode: "date" }).notNull(),
  createdAt: timestamp("created_at", { withTimezone: true, mode: "date" }).defaultNow().notNull(),
  updatedAt: timestamp("updated_at", { withTimezone: true, mode: "date" }).defaultNow().notNull().$onUpdate(() => new Date()),
}, (table) => ({
  subscriptionIdIdx: index("exposures_subscription_id_idx").on(table.subscriptionId),
  watchlistItemIdIdx: index("exposures_watchlist_item_id_idx").on(table.watchlistItemId),
  sourceIdx: index("exposures_source_idx").on(table.source),
  severityIdx: index("exposures_severity_idx").on(table.severity),
  detectedAtIdx: index("exposures_detected_at_idx").on(table.detectedAt),
}));
