import {
  db,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { role } from "./role";
import { permission } from "./permission";

export interface CreateRolePermissionTypeParams {
  fields?: Record<string, unknown>;
}

export function createRolePermissionType(params: CreateRolePermissionTypeParams) {
  return db
    .type("RolePermission", {
      roleId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: role },
          backward: "rolePermissions",
        })
        .description("Foreign key to Role"),
      permissionId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: permission },
          backward: "rolePermissions",
        })
        .description("Foreign key to Permission"),
      ...params.fields,
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["roleId", "permissionId"],
      unique: true,
      name: "role_permission_unique_idx",
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const rolePermission = createRolePermissionType({});
