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: "reactivateUser",
  operation: "mutation",
  input: {
    userId: t.string().description("ID of the user to reactivate"),
  },
  body: async (context) => {
    const db = getDB("main-db");
    const result = await db.transaction().execute(async (trx) => {
      const cmdResult = await umModules.commands.reactivateUser(
        trx,
        { userId: context.input.userId },
        createContext(context),
      );
      if (!cmdResult.ok) {
        switch (cmdResult.error.code) {
          case "USER_MANAGEMENT_USER_NOT_FOUND":
            throw new Error(`User ${context.input.userId} does not exist`);
          case "USER_MANAGEMENT_INVALID_STATUS_TRANSITION":
            throw new Error("User is not in INACTIVE status");
          case "INSUFFICIENT_PERMISSION":
            throw cmdResult.error;
        }
      }
      return {
        id: cmdResult.value.user.id,
        status: cmdResult.value.user.status,
      };
    });

    await db
      .transaction()
      .execute(async (trx) => {
        await auditModules.commands.logAuditEvent(
          trx,
          {
            eventId: crypto.randomUUID(),
            actorType: "USER",
            actorId: context.user.id,
            entityType: "User",
            entityId: result.id,
            operationType: "UPDATE",
            changes: [{ fieldName: "status", oldValue: "INACTIVE", newValue: result.status }],
          },
          createContext(context),
        );
      })
      .catch(() => undefined);

    return result;
  },
  output: t
    .object({
      id: t.string().description("User ID"),
      status: t.string().description("Updated status"),
    })
    .description("Reactivated user"),
});
