import {
  mysqlTable,
  varchar,
  timestamp,
  text,
  int,
  tinyint,
  json,
  index,
} from "drizzle-orm/mysql-core";

export const textbooks = mysqlTable(
  "content_textbooks",
  {
    id: varchar("id", { length: 32 }).notNull().primaryKey(),
    title: varchar("title", { length: 255 }).notNull(),
    subjectId: varchar("subject_id", { length: 32 }).notNull(),
    gradeId: varchar("grade_id", { length: 32 }).notNull(),
    version: varchar("version", { length: 32 }).notNull().default("1.0"),
    status: varchar("status", { length: 32 }).notNull().default("draft"),
    tenantId: varchar("tenant_id", { length: 32 }),
    metadata: json("metadata").$type<Record<string, unknown> | null>(),
    createdAt: timestamp("created_at").notNull().defaultNow(),
    updatedAt: timestamp("updated_at").notNull().defaultNow().onUpdateNow(),
  },
  (table) => ({
    subjectGradeIdx: index("idx_textbooks_subject_grade").on(
      table.subjectId,
      table.gradeId,
    ),
    statusIdx: index("idx_textbooks_status").on(table.status),
    tenantIdx: index("idx_textbooks_tenant").on(table.tenantId),
  }),
);

export const chapters = mysqlTable(
  "content_chapters",
  {
    id: varchar("id", { length: 32 }).notNull().primaryKey(),
    textbookId: varchar("textbook_id", { length: 32 }).notNull(),
    title: varchar("title", { length: 255 }).notNull(),
    order: int("order_num").notNull().default(0),
    parentId: varchar("parent_id", { length: 32 }),
    status: varchar("status", { length: 32 }).notNull().default("draft"),
    createdAt: timestamp("created_at").notNull().defaultNow(),
    updatedAt: timestamp("updated_at").notNull().defaultNow().onUpdateNow(),
  },
  (table) => ({
    textbookOrderIdx: index("idx_chapters_textbook_order").on(
      table.textbookId,
      table.order,
    ),
    parentIdx: index("idx_chapters_parent").on(table.parentId),
  }),
);

export const knowledgePoints = mysqlTable(
  "content_knowledge_points",
  {
    id: varchar("id", { length: 32 }).notNull().primaryKey(),
    chapterId: varchar("chapter_id", { length: 32 }).notNull(),
    title: varchar("title", { length: 255 }).notNull(),
    description: text("description"),
    difficulty: tinyint("difficulty").notNull().default(3),
    metadata: json("metadata").$type<Record<string, unknown> | null>(),
    createdAt: timestamp("created_at").notNull().defaultNow(),
    updatedAt: timestamp("updated_at").notNull().defaultNow().onUpdateNow(),
  },
  (table) => ({
    chapterIdx: index("idx_kp_chapter").on(table.chapterId),
  }),
);

export type Textbook = typeof textbooks.$inferSelect;
export type NewTextbook = typeof textbooks.$inferInsert;
export type Chapter = typeof chapters.$inferSelect;
export type NewChapter = typeof chapters.$inferInsert;
export type KnowledgePoint = typeof knowledgePoints.$inferSelect;
export type NewKnowledgePoint = typeof knowledgePoints.$inferInsert;
