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: "updateRole",
  operation: "mutation",
  input: {
    roleId: t.uuid().description("Role ID"),
    name: t.string({ optional: true }).description("New role name"),
    description: t.string({ optional: true }).description("New role description"),
    permissions: t.string({ array: true }).description("Desired permission keys"),
  },
  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 ctx = createContext(context);

      const updateInput: {
        id: string;
        name?: string;
        description?: string | null;
        permissions?: string[];
      } = {
        id: context.input.roleId,
        permissions: allPermissions,
      };
      if (context.input.name != null) updateInput.name = context.input.name;
      if (context.input.description !== undefined)
        updateInput.description = context.input.description;

      const updateResult = await umModules.commands.updateRole(trx, updateInput, ctx);
      if (!updateResult.ok) {
        switch (updateResult.error.code) {
          case "USER_MANAGEMENT_ROLE_NOT_FOUND":
            throw new Error(`Role ${context.input.roleId} does not exist`);
          case "USER_MANAGEMENT_ROLE_ALREADY_EXISTS":
            throw new Error(`A role with name "${context.input.name}" already exists`);
          case "USER_MANAGEMENT_ROLE_NOT_ACTIVE":
            throw new Error(`Role ${context.input.roleId} is not active`);
          case "USER_MANAGEMENT_MISSING_REQUIRED_FIELD":
            throw new Error("Role name cannot be empty");
          case "USER_MANAGEMENT_INVALID_PERMISSION":
            throw new Error(`Invalid permission format: ${updateResult.error.message}`);
          case "INSUFFICIENT_PERMISSION":
            throw updateResult.error;
          default:
            throw updateResult.error satisfies never;
        }
      }

      return { roleId: context.input.roleId };
    });

    return { roleId: result.roleId };
  },
  output: t
    .object({
      roleId: t.uuid().description("Role ID"),
    })
    .description("Role update result"),
});
