import { db } from "@tailor-platform/sdk";
import { defaultGqlPermission, defaultPermission } from "../../../shared/modelPermissions";
import { role } from "./role";
import { user } from "./user";

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

export function createUserRoleType(params: CreateUserRoleTypeParams) {
  return db
    .type("UserRole", {
      userId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: user },
          backward: "userRoles",
        })
        .description("Foreign key to User"),
      roleId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: role },
          backward: "userRoles",
        })
        .description("Foreign key to Role"),
      ...params.fields,
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["userId", "roleId"],
      unique: true,
      name: "user_role_unique_idx",
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const userRole = createUserRoleType({});
