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

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(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const userRole = createUserRoleType({});
