import {
  mysqlTable,
  varchar,
  char,
  timestamp,
  text,
  mysqlEnum,
} from "drizzle-orm/mysql-core";

export const users = mysqlTable("iam_users", {
  id: char("id", { length: 36 }).notNull().primaryKey(),
  email: varchar("email", { length: 255 }).notNull().unique(),
  passwordHash: varchar("password_hash", { length: 255 }).notNull(),
  name: varchar("name", { length: 100 }).notNull(),
  status: varchar("status", { length: 20 }).notNull().default("active"),
  dataScope: mysqlEnum("data_scope", [
    "self",
    "class",
    "grade",
    "school",
    "district",
    "all",
  ])
    .notNull()
    .default("self"),
  createdAt: timestamp("created_at").notNull().defaultNow(),
  updatedAt: timestamp("updated_at").notNull().defaultNow().onUpdateNow(),
});

export const roles = mysqlTable("iam_roles", {
  id: char("id", { length: 36 }).notNull().primaryKey(),
  name: varchar("name", { length: 50 }).notNull().unique(),
  description: varchar("description", { length: 255 }),
});

export const userRoles = mysqlTable("iam_user_roles", {
  userId: char("user_id", { length: 36 }).notNull(),
  roleId: char("role_id", { length: 36 }).notNull(),
  createdAt: timestamp("created_at").notNull().defaultNow(),
});

export const permissions = mysqlTable("iam_permissions", {
  id: char("id", { length: 36 }).notNull().primaryKey(),
  name: varchar("name", { length: 100 }).notNull().unique(),
  resource: varchar("resource", { length: 50 }).notNull(),
  action: varchar("action", { length: 50 }).notNull(),
});

export const rolePermissions = mysqlTable("iam_role_permissions", {
  roleId: char("role_id", { length: 36 }).notNull(),
  permissionId: char("permission_id", { length: 36 }).notNull(),
});

export const refreshTokens = mysqlTable("iam_refresh_tokens", {
  id: char("id", { length: 36 }).notNull().primaryKey(),
  userId: char("user_id", { length: 36 }).notNull(),
  tokenHash: varchar("token_hash", { length: 255 }).notNull(),
  expiresAt: timestamp("expires_at").notNull(),
  revokedAt: timestamp("revoked_at"),
  createdAt: timestamp("created_at").notNull().defaultNow(),
});

// 视口配置表（4 层模型：L1 导航 / L2 路由 / L3 组件 / L4 数据）
// 每条记录代表一个角色可见的导航项
export const roleViewports = mysqlTable("iam_role_viewports", {
  id: char("id", { length: 36 }).notNull().primaryKey(),
  roleId: char("role_id", { length: 36 }).notNull(),
  viewportKey: varchar("viewport_key", { length: 50 }).notNull(),
  label: varchar("label", { length: 100 }).notNull(),
  route: varchar("route", { length: 200 }).notNull(),
  icon: varchar("icon", { length: 50 }),
  sortOrder: varchar("sort_order", { length: 10 }).notNull().default("0"),
  requiredPermission: varchar("required_permission", { length: 100 }),
  // L3 组件级配置（JSON）：控制组件内按钮/操作的显隐
  componentConfig: text("component_config"),
});

export type User = typeof users.$inferSelect;
export type Role = typeof roles.$inferSelect;
export type Permission = typeof permissions.$inferSelect;
export type RoleViewport = typeof roleViewports.$inferSelect;
