import { createContext } from "@tailor-platform/erp-kit/app";
import { createResolver, t } from "@tailor-platform/sdk";
import { getDB } from "@/generated/kysely-tailordb";
import { umModules } from "@/modules";

const AUTO_ASSIGNED_SCOPES = ["user-management:profile"];

export default createResolver({
  name: "createRole",
  operation: "mutation",
  input: {
    name: t.string().description("Role name"),
    description: t.string({ optional: true }).description("Role description"),
    permissions: t.string({ array: true }).description("Permission keys to assign"),
  },
  body: async (context) => {
    const db = getDB("main-db");
    const allPermissions = [...new Set([...context.input.permissions, ...AUTO_ASSIGNED_SCOPES])];

    const result = await db.transaction().execute(async (trx) => {
      const cmdResult = await umModules.commands.createRole(
        trx,
        {
          name: context.input.name,
          description: context.input.description ?? undefined,
          permissions: allPermissions,
        },
        createContext(context),
      );
      if (!cmdResult.ok) {
        switch (cmdResult.error.code) {
          case "USER_MANAGEMENT_ROLE_ALREADY_EXISTS":
            throw new Error(`A role with name "${context.input.name}" already exists`);
          case "USER_MANAGEMENT_MISSING_REQUIRED_FIELD":
            throw new Error("Role name is required");
          case "USER_MANAGEMENT_INVALID_PERMISSION":
            throw new Error(`Invalid permission format: ${cmdResult.error.message}`);
          case "INSUFFICIENT_PERMISSION":
            throw cmdResult.error;
          default:
            throw cmdResult.error satisfies never;
        }
      }

      return {
        id: cmdResult.value.role.id,
        name: cmdResult.value.role.name,
        description: cmdResult.value.role.description ?? "",
      };
    });

    return result;
  },
  output: t
    .object({
      id: t.uuid().description("Role ID"),
      name: t.string().description("Role name"),
      description: t.string().description("Role description"),
    })
    .description("Created role"),
});
