import {
  pgTable,
  serial,
  timestamp,
  integer,
  index,
} from "drizzle-orm/pg-core";
import { usersTable } from "./users";
import { rolesTable } from "./roles";

export const rolePermissionAuditTable = pgTable(
  "role_permission_audit",
  {
    id: serial("id").primaryKey(),
    roleId: integer("role_id")
      .notNull()
      .references(() => rolesTable.id, { onDelete: "cascade" }),
    actorUserId: integer("actor_user_id").references(() => usersTable.id, {
      onDelete: "set null",
    }),
    previousPermissionIds: integer("previous_permission_ids")
      .array()
      .notNull()
      .default([]),
    newPermissionIds: integer("new_permission_ids")
      .array()
      .notNull()
      .default([]),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => [index("role_permission_audit_role_idx").on(t.roleId, t.createdAt)],
);

export type RolePermissionAudit = typeof rolePermissionAuditTable.$inferSelect;
