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: "deactivateProduct",
  operation: "mutation",
  input: {
    id: t.uuid().description("Product ID"),
  },
  body: async (context) => {
    const db = getDB("main-db");
    const result = await db.transaction().execute(async (trx) => {
      const cmdResult = await pmModules.commands.deactivateProduct(
        trx,
        { id: context.input.id },
        createContext(context),
      );
      if (!cmdResult.ok) {
        switch (cmdResult.error.code) {
          case "PRODUCT_MANAGEMENT_PRODUCT_NOT_FOUND":
            throw new Error(`Product ${context.input.id} does not exist`);
          case "PRODUCT_MANAGEMENT_INVALID_STATE_TRANSITION":
            throw new Error("Product cannot be deactivated from its current status");
          case "INSUFFICIENT_PERMISSION":
            throw cmdResult.error;
          default:
            throw cmdResult.error satisfies never;
        }
      }
      return {
        id: cmdResult.value.product.id,
        status: cmdResult.value.product.status,
      };
    });

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