import type { AdminProductVariant, StoreProduct } from '@medusajs/types';

type Product = {
  metadata?: {
    analysisElementMedusaProductIds?: string;
  } | null;
  variant?: {
    metadata?: {
      analysisElementMedusaProductIds?: string;
    } | null;
  } | null;
} | null;

export const getAnalysisElementMedusaProductIds = (
  products: (Pick<StoreProduct, 'metadata'> & {
    variant?: Pick<AdminProductVariant, 'metadata'>;
  })[],
) => {
  if (!products) {
    return [];
  }

  const mapped = products
    .flatMap((product) => {
      const value = (
        product as Product
      )?.metadata?.analysisElementMedusaProductIds?.replaceAll("'", '"');
      const value_variant = (
        product as Product
      )?.variant?.metadata?.analysisElementMedusaProductIds?.replaceAll(
        "'",
        '"',
      );

      const result: string[] = [];
      try {
        if (value) {
          result.push(...JSON.parse(value as string));
        }
      } catch (e) {
        console.error(
          'Failed to parse analysisElementMedusaProductIds from analysis package variant, possibly invalid format',
          e,
        );
      }
      try {
        if (value_variant) {
          result.push(...JSON.parse(value_variant as string));
        }
      } catch (e) {
        console.error(
          'Failed to parse analysisElementMedusaProductIds from analysis package, possibly invalid format',
          e,
        );
      }

      return result;
    })
    .filter(Boolean) as string[];

  return [...new Set(mapped)];
};
