import { pgTable, text, timestamp, uniqueIndex, index, uuid, jsonb, integer } from "drizzle-orm/pg-core";
import { users } from "./auth";
import { alertSource, alertCategory, normalizedAlertSeverity, correlationStatus } from "./enums";

export const correlationGroups = pgTable("correlation_groups", {
  id: uuid("id").defaultRandom().primaryKey(),
  userId: uuid("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
  entities: jsonb("entities").notNull(),
  highestSeverity: normalizedAlertSeverity("highest_severity").notNull(),
  status: correlationStatus("status").default("ACTIVE").notNull(),
  alertCount: integer("alert_count").default(0).notNull(),
  summary: text("summary"),
  resolvedAt: timestamp("resolved_at", { withTimezone: true, mode: "date" }),
  createdAt: timestamp("created_at", { withTimezone: true, mode: "date" }).defaultNow().notNull(),
  updatedAt: timestamp("updated_at", { withTimezone: true, mode: "date" }).defaultNow().notNull().$onUpdate(() => new Date()),
}, (table) => ({
  userIdIdx: index("correlation_groups_user_id_idx").on(table.userId),
  statusIdx: index("correlation_groups_status_idx").on(table.status),
  userIdStatusIdx: index("correlation_groups_user_id_status_idx").on(table.userId, table.status),
  createdAtIdx: index("correlation_groups_created_at_idx").on(table.createdAt),
}));

export const normalizedAlerts = pgTable("normalized_alerts", {
  id: uuid("id").defaultRandom().primaryKey(),
  source: alertSource("source").notNull(),
  category: alertCategory("category").notNull(),
  severity: normalizedAlertSeverity("severity").notNull(),
  userId: uuid("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
  title: text("title").notNull(),
  description: text("description").notNull(),
  entities: jsonb("entities").notNull(),
  sourceAlertId: text("source_alert_id").notNull(),
  groupId: uuid("group_id").references(() => correlationGroups.id),
  payload: jsonb("payload"),
  createdAt: timestamp("created_at", { withTimezone: true, mode: "date" }).notNull(),
  updatedAt: timestamp("updated_at", { withTimezone: true, mode: "date" }).defaultNow().notNull().$onUpdate(() => new Date()),
}, (table) => ({
  sourceAlertIdUnique: uniqueIndex("normalized_alerts_source_alert_id_unique").on(table.sourceAlertId),
  userIdIdx: index("normalized_alerts_user_id_idx").on(table.userId),
  groupIdIdx: index("normalized_alerts_group_id_idx").on(table.groupId),
  sourceIdx: index("normalized_alerts_source_idx").on(table.source),
  severityIdx: index("normalized_alerts_severity_idx").on(table.severity),
  createdAtIdx: index("normalized_alerts_created_at_idx").on(table.createdAt),
  userIdCreatedAtIdx: index("normalized_alerts_user_id_created_at_idx").on(table.userId, table.createdAt),
}));
