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

export default createResolver({
  name: "deactivateUser",
  operation: "mutation",
  input: {
    userId: t.uuid().description("ID of the user to deactivate"),
  },
  body: async (context) => {
    if (context.input.userId === context.user.id) {
      throw new Error("Cannot deactivate your own account");
    }

    const db = getDB("main-db");
    const result = await db.transaction().execute(async (trx) => {
      const cmdResult = await umModules.commands.deactivateUser(
        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 ACTIVE status");
          case "INSUFFICIENT_PERMISSION":
            throw cmdResult.error;
          default:
            throw cmdResult.error satisfies never;
        }
      }
      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: createContext(context).actorId,
            entityType: "User",
            entityId: result.id,
            operationType: "UPDATE",
            changes: [{ fieldName: "status", newValue: result.status }],
          },
          createContext(context),
        );
      })
      .catch(() => undefined);

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