type OptionValue = {
	id?: number;
	label: string;
	is_default?: boolean;
	swatch_value?: string | string[] | null;
	price_adjuster?: number | null;
};

type OptionType = {
	id?: number;
	name: string;
	type: string;
	required: boolean;
	is_modifier: boolean;
	config: Record<string, unknown>;
	values: OptionValue[];
};

export const buildColorMap = (product: { options?: any[] }) => {
	const colorMap: Record<number, string | string[]> = {};
	const options = product.options ?? [];
	if (options.length === 0) return colorMap;

	const colorOptions = options.find((opt: any) => opt.type === "swatch");
	if (!colorOptions?.option_values) return colorMap;

	colorOptions.option_values.forEach((value: any) => {
		if (value.value_data?.colors) {
			colorMap[value.id] = value.value_data.colors;
		}
		if (value.value_data?.image_url) {
			colorMap[value.id] = value.value_data.image_url;
		}
	});

	return colorMap;
};

export const buildOptionType = (product: { options?: any[]; modifiers?: any[] }): OptionType[] => {
	const hasOptions = (product.options?.length ?? 0) > 0;
	const source = hasOptions ? product.options! : (product.modifiers ?? []);

	if (source.length === 0) return [];

	return source.map((item: any) => {
		const optionValues = item.option_values ?? [];

		if (hasOptions) {
			return {
				id: item.id,
				name: item.display_name,
				type: item.type,
				required: item.required ?? false,
				is_modifier: false,
				config: item.config ?? {},
				values: optionValues.map((val: any) => {
					if (item.type !== "swatch") {
						return {
							id: val.id,
							label: val.label,
							is_default: val.is_default ?? false,
						};
					}
					const valueData = val.value_data || {};
					let swatchValue: string | string[] | null = null;
					if (valueData.colors?.length) {
						swatchValue = valueData.colors;
					} else if (valueData.image_url) {
						swatchValue = valueData.image_url;
					}
					return {
						id: val.id,
						label: val.label,
						is_default: val.is_default ?? false,
						swatch_value: swatchValue,
					};
				}),
			};
		}

		return {
			id: item.id,
			name: item.display_name,
			type: item.type,
			required: item.required ?? false,
			is_modifier: true,
			config: item.config ?? {},
			values: optionValues.map((val: any) => ({
				id: val.id,
				label: val.label,
				is_default: val.is_default ?? false,
				price_adjuster: val.adjusters?.price?.adjuster_value ?? null,
			})),
		};
	});
};
