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

// DataScope 6 级（president §3.2：SUBJECT 替代 DISTRICT）
export const DATA_SCOPES = [
  "self",
  "subject",
  "class",
  "grade",
  "school",
  "all",
] as const;
export type DataScope = (typeof DATA_SCOPES)[number];

// 三层角色模型（P2.2：system / organization / temporary）
export const ROLE_TYPES = ["system", "organization", "temporary"] as const;
export type RoleType = (typeof ROLE_TYPES)[number];

// 视口 4 层（admin / teacher / student / parent）
export const VIEWPORT_LEVELS = [
  "admin",
  "teacher",
  "student",
  "parent",
] as const;
export type ViewportLevel = (typeof VIEWPORT_LEVELS)[number];

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", DATA_SCOPES).notNull().default("self"),
  // 密码策略：记录上次修改时间，用于过期校验
  passwordChangedAt: timestamp("password_changed_at").notNull().defaultNow(),
  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 }),
    // 三层角色模型：system(系统预设) / organization(组织分配) / temporary(临时授权)
    roleType: mysqlEnum("role_type", ROLE_TYPES).notNull().default("system"),
    // 三层优先级：system=0(最高) / organization=1 / temporary=2
    level: int("level").notNull().default(0),
    createdAt: timestamp("created_at").notNull().defaultNow(),
    updatedAt: timestamp("updated_at").notNull().defaultNow().onUpdateNow(),
  },
  (table) => ({
    roleTypeIdx: index("idx_iam_roles_type").on(table.roleType),
  }),
);

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(),
  },
  (table) => ({
    pk: index("idx_iam_user_roles_pk").on(table.userId, table.roleId),
    roleIdx: index("idx_iam_user_roles_role").on(table.roleId),
  }),
);

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(),
  },
  (table) => ({
    pk: index("idx_iam_role_permissions_pk").on(
      table.roleId,
      table.permissionId,
    ),
    permIdx: index("idx_iam_role_permissions_perm").on(table.permissionId),
  }),
);

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(),
    // JWT ID，用于黑名单追踪
    jti: varchar("jti", { length: 36 }),
    expiresAt: timestamp("expires_at").notNull(),
    revokedAt: timestamp("revoked_at"),
    createdAt: timestamp("created_at").notNull().defaultNow(),
  },
  (table) => ({
    userIdx: index("idx_iam_refresh_tokens_user").on(table.userId),
    jtiIdx: index("idx_iam_refresh_tokens_jti").on(table.jti),
  }),
);

// 视口配置表（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 }),
    // 视口层级：admin / teacher / student / parent
    level: mysqlEnum("level", VIEWPORT_LEVELS).notNull().default("teacher"),
    // L3 组件级配置（JSON）：控制组件内按钮/操作的显隐
    componentConfig: text("component_config"),
  },
  (table) => ({
    roleIdx: index("idx_iam_role_viewports_role").on(table.roleId),
    levelIdx: index("idx_iam_role_viewports_level").on(table.level),
  }),
);

// 学生-家长关系表（I6 裁决：表名 iam_student_guardians）
export const studentGuardians = mysqlTable(
  "iam_student_guardians",
  {
    id: char("id", { length: 36 }).notNull().primaryKey(),
    studentId: char("student_id", { length: 36 }).notNull(),
    guardianId: char("guardian_id", { length: 36 }).notNull(),
    relation: varchar("relation", { length: 20 }).notNull(),
    createdAt: timestamp("created_at").notNull().defaultNow(),
  },
  (table) => ({
    guardianStudentUniq: uniqueIndex("uniq_student_guardian").on(
      table.studentId,
      table.guardianId,
    ),
    guardianIdx: index("idx_iam_student_guardians_guardian").on(
      table.guardianId,
    ),
    studentIdx: index("idx_iam_student_guardians_student").on(table.studentId),
  }),
);

// 审计日志表（president §5.5：审计日志归 iam）
export const userAuditLog = mysqlTable(
  "iam_user_audit_log",
  {
    id: char("id", { length: 36 }).notNull().primaryKey(),
    actorUserId: char("actor_user_id", { length: 36 }).notNull(),
    action: varchar("action", { length: 50 }).notNull(),
    resourceType: varchar("resource_type", { length: 50 }).notNull(),
    resourceId: varchar("resource_id", { length: 36 }).notNull(),
    beforeState: text("before_state"),
    afterState: text("after_state"),
    ip: varchar("ip", { length: 45 }),
    userAgent: varchar("user_agent", { length: 255 }),
    traceId: varchar("trace_id", { length: 64 }),
    createdAt: timestamp("created_at").notNull().defaultNow(),
  },
  (table) => ({
    actorIdx: index("idx_iam_audit_actor").on(table.actorUserId),
    resourceIdx: index("idx_iam_audit_resource").on(
      table.resourceType,
      table.resourceId,
    ),
    createdAtIdx: index("idx_iam_audit_created").on(table.createdAt),
  }),
);

// 密码历史表（密码重用限制）
export const passwordHistory = mysqlTable(
  "iam_password_history",
  {
    id: char("id", { length: 36 }).notNull().primaryKey(),
    userId: char("user_id", { length: 36 }).notNull(),
    passwordHash: varchar("password_hash", { length: 255 }).notNull(),
    createdAt: timestamp("created_at").notNull().defaultNow(),
  },
  (table) => ({
    userIdx: index("idx_iam_password_history_user").on(table.userId),
  }),
);

export type User = typeof users.$inferSelect;
export type Role = typeof roles.$inferSelect;
export type Permission = typeof permissions.$inferSelect;
export type RoleViewport = typeof roleViewports.$inferSelect;
export type StudentGuardian = typeof studentGuardians.$inferSelect;
export type AuditLog = typeof userAuditLog.$inferSelect;
export type PasswordHistoryEntry = typeof passwordHistory.$inferSelect;
