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

// ---------------------------------------------------------------------------
// Audit schema — aligned to PRODUCTION as of 2026-05-19 baseline.
//
// Drift corrected at baseline:
//  - audit_log: added resource_id / resource_type (legacy 0010_audit_log);
//               metadata is JSONB (was modelled as text); action is varchar(50)
//  - log_corrections: append-only-with-corrections record, was missing here
// ---------------------------------------------------------------------------

export const auditLog = pgTable(
  "audit_log",
  {
    id: uuid("id").defaultRandom().primaryKey(),
    familyId: uuid("family_id"),
    userId: uuid("user_id"),
    action: varchar("action", { length: 50 }).notNull(),
    resourceType: varchar("resource_type", { length: 50 }),
    resourceId: uuid("resource_id"),
    ipAddress: varchar("ip_address", { length: 45 }),
    userAgent: text("user_agent"),
    metadata: jsonb("metadata").default({}),
    createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(),
  },
  (table) => [
    index("audit_family_idx").on(table.familyId, table.createdAt),
    index("idx_audit_log_action").on(table.action),
    index("idx_audit_log_created").on(table.createdAt),
    index("idx_audit_log_family").on(table.familyId),
    index("idx_audit_log_user").on(table.userId),
  ]
);

// Append-only correction trail for medical dose logs.
export const logCorrections = pgTable(
  "log_corrections",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    familyId: uuid("family_id").notNull(),
    doseId: uuid("dose_id").notNull(),
    originalValue: jsonb("original_value").notNull(),
    correctedValue: jsonb("corrected_value").notNull(),
    reason: text("reason"),
    correctedBy: uuid("corrected_by"),
    createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(),
  },
  (table) => [index("log_corrections_dose_idx").on(table.doseId)]
);

// Error / crash events (client + server). Written by src/lib/error-log.ts and
// the error boundaries; surfaced in the admin panel at /admin/errors.
export const errorEvents = pgTable(
  "error_events",
  {
    id: uuid("id").defaultRandom().primaryKey(),
    level: varchar("level", { length: 20 }).notNull().default("error"),
    source: varchar("source", { length: 20 }).notNull().default("client"),
    message: text("message").notNull(),
    stack: text("stack"),
    url: text("url"),
    digest: varchar("digest", { length: 120 }),
    userId: uuid("user_id"),
    familyId: uuid("family_id"),
    userAgent: text("user_agent"),
    metadata: jsonb("metadata").default({}),
    createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(),
  },
  (table) => [
    index("idx_error_events_created").on(table.createdAt),
    index("idx_error_events_source").on(table.source),
    index("idx_error_events_message").on(table.message),
  ]
);

export type AuditLog = typeof auditLog.$inferSelect;
export type LogCorrection = typeof logCorrections.$inferSelect;
export type ErrorEvent = typeof errorEvents.$inferSelect;
