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";

export default createResolver({
  name: "deactivateRole",
  operation: "mutation",
  input: {
    roleId: t.uuid().description("ID of the role to deactivate"),
  },
  body: async (context) => {
    const db = getDB("main-db");
    const result = await db.transaction().execute(async (trx) => {
      const cmdResult = await umModules.commands.deactivateRole(
        trx,
        { roleId: context.input.roleId },
        createContext(context),
      );
      if (!cmdResult.ok) {
        switch (cmdResult.error.code) {
          case "USER_MANAGEMENT_ROLE_NOT_FOUND":
            throw new Error(`Role ${context.input.roleId} does not exist`);
          case "USER_MANAGEMENT_INVALID_STATUS_TRANSITION":
            throw new Error("Role is not in ACTIVE status");
          case "USER_MANAGEMENT_ROLE_HAS_ACTIVE_ASSIGNMENTS":
            throw new Error("Role still has active user assignments — revoke them first");
          case "INSUFFICIENT_PERMISSION":
            throw cmdResult.error;
          default:
            throw cmdResult.error satisfies never;
        }
      }
      return {
        id: cmdResult.value.role.id,
        status: cmdResult.value.role.status,
      };
    });

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