import type {DocumentActionComponent} from "sanity";
import {useClient} from "sanity";

const API_VERSION = "2026-03-26";

type ProductThemeRow = {
  _id: string;
  themes?: Array<{_key?: string; _ref?: string}>;
};

async function detachThemeFromAllProducts(client: ReturnType<typeof useClient>, themeId: string) {
  const products = await client.fetch<ProductThemeRow[]>(
    `*[_type == "product" && references($themeId)]{
      _id,
      themes[]{
        _key,
        _ref
      }
    }`,
    {themeId},
  );

  if (!products.length) {
    return;
  }

  let transaction = client.transaction();

  for (const product of products) {
    const nextThemes = (product.themes || []).filter((theme) => theme?._ref !== themeId);
    transaction = transaction.patch(product._id, (patch) => patch.set({themes: nextThemes}));
  }

  await transaction.commit();
}

export function createThemeDeleteAction(originalDeleteAction: DocumentActionComponent): DocumentActionComponent {
  return function ThemeDeleteAction(props) {
    const client = useClient({apiVersion: API_VERSION});
    const originalResult = originalDeleteAction(props);

    if (!originalResult) {
      return null;
    }

    const themeId = props.id.replace(/^drafts\./, "");

    return {
      ...originalResult,
      onHandle: async () => {
        if (themeId) {
          await detachThemeFromAllProducts(client, themeId);
        }

        await originalResult.onHandle?.();
      },
    };
  };
}
