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

export default createResolver({
  name: "deleteAttribute",
  operation: "mutation",
  input: {
    id: t.uuid().description("Attribute ID"),
  },
  body: async (context) => {
    const db = getDB("main-db");
    const result = await db.transaction().execute(async (trx) => {
      const cmdResult = await pmModules.commands.deleteProductAttribute(
        trx,
        {
          id: context.input.id,
        },
        createContext(context),
      );
      if (!cmdResult.ok) {
        switch (cmdResult.error.code) {
          case "PRODUCT_MANAGEMENT_ATTRIBUTE_NOT_FOUND":
            throw new Error(`Attribute not found: ${context.input.id}`);
          case "PRODUCT_MANAGEMENT_ATTRIBUTE_IN_USE":
            throw new Error(`Attribute is in use and cannot be deleted: ${context.input.id}`);
          case "INSUFFICIENT_PERMISSION":
            throw cmdResult.error;
          default:
            throw cmdResult.error satisfies never;
        }
      }
      return {
        id: cmdResult.value.id,
      };
    });

    return result;
  },
  output: t
    .object({
      id: t.uuid().description("Deleted attribute ID"),
    })
    .description("Deleted attribute"),
});
