import type { DashboardDocument } from "@dimensionlab/dashboard-model";
import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";

export const dashboardDocuments = sqliteTable("dashboard_documents", {
  id: text("id").primaryKey(),
  currentRevisionId: text("current_revision_id"),
  createdAt: integer("created_at", { mode: "timestamp_ms" }).notNull(),
  updatedAt: integer("updated_at", { mode: "timestamp_ms" }).notNull(),
});

export const dashboardRevisions = sqliteTable(
  "dashboard_revisions",
  {
    id: text("id").primaryKey(),
    dashboardId: text("dashboard_id").notNull(),
    schemaVersion: text("schema_version").notNull(),
    document: text("document", { mode: "json" }).$type<DashboardDocument>().notNull(),
    actor: text("actor").notNull(),
    message: text("message"),
    operation: text("operation", {
      enum: ["seed", "commit", "rollback"],
    }).notNull(),
    sourceRevisionId: text("source_revision_id"),
    createdAt: integer("created_at", { mode: "timestamp_ms" }).notNull(),
  },
  (table) => [
    index("idx_dashboard_revisions_dashboard_created").on(
      table.dashboardId,
      table.createdAt,
    ),
  ],
);

export const dashboardDbSchema = {
  dashboardDocuments,
  dashboardRevisions,
};

export type DashboardRevisionOperation = "seed" | "commit" | "rollback";
