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

export default createResolver({
  name: "assignPermissionToRole",
  operation: "mutation",
  input: {
    roleId: t.string().description("Role ID"),
    permissionId: t.string().description("Permission ID to assign"),
  },
  body: async (context) => {
    const db = getDB("main-db");
    const result = await db.transaction().execute(async (trx) => {
      const cmdResult = await umModules.commands.assignPermissionToRole(
        trx,
        {
          roleId: context.input.roleId,
          permissionId: context.input.permissionId,
        },
        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_PERMISSION_NOT_FOUND":
            throw new Error(`Permission ${context.input.permissionId} does not exist`);
          case "INSUFFICIENT_PERMISSION":
            throw cmdResult.error;
        }
      }
      return {
        roleId: context.input.roleId,
        permissionId: context.input.permissionId,
      };
    });

    await db
      .transaction()
      .execute(async (trx) => {
        await auditModules.commands.logAuditEvent(
          trx,
          {
            eventId: crypto.randomUUID(),
            actorType: "USER",
            actorId: context.user.id,
            entityType: "RolePermission",
            entityId: `${result.roleId}:${result.permissionId}`,
            operationType: "CREATE",
            changes: [
              { fieldName: "roleId", newValue: result.roleId },
              { fieldName: "permissionId", newValue: result.permissionId },
            ],
          },
          createContext(context),
        );
      })
      .catch(() => undefined);

    return result;
  },
  output: t
    .object({
      roleId: t.string().description("Role ID"),
      permissionId: t.string().description("Assigned permission ID"),
    })
    .description("Permission assignment result"),
});
