<?php

namespace Fotogenic_AI\Compat\WooCommerce;

use Fotogenic_AI\ProductMediaWriteAdapter;
use Fotogenic_AI\Workflow_Item_Identity;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

final class Product_Media_Write_Adapter_WooCommerce implements ProductMediaWriteAdapter {
	/** @return array|\WP_Error */
	public function apply_to_target( array $target, array $attachment_ids, bool $set_featured, bool $add_gallery ) {
		$resolved = $this->resolve_exact_target( $target );
		if ( is_wp_error( $resolved ) ) {
			return $resolved;
		}
		$normalized = $resolved['target'];
		$product = $resolved['product'];
		$attachment_ids = array_values( array_unique( array_filter( array_map( 'absint', $attachment_ids ) ) ) );
		if ( empty( $attachment_ids ) || ( ! $set_featured && ! $add_gallery ) ) {
			return $this->invalid_target();
		}
		if ( $add_gallery && ( 'product' !== (string) $normalized['targetType'] || empty( $normalized['destinationCapabilities']['addGallery'] ) ) ) {
			return new \WP_Error(
				'fotogenic_ai_variation_gallery_unsupported',
				__( 'Gallery actions are not available for the selected variation.', 'fotogenic-ai' ),
				[ 'status' => 400 ]
			);
		}

		$changed = false;
		if ( $set_featured && (int) $product->get_image_id( 'edit' ) !== (int) $attachment_ids[0] ) {
			$product->set_image_id( (int) $attachment_ids[0] );
			$changed = true;
		}
		if ( $add_gallery ) {
			$current_gallery = array_values( array_filter( array_map( 'absint', (array) $product->get_gallery_image_ids( 'edit' ) ) ) );
			$next_gallery = array_values( array_unique( array_merge( $current_gallery, $attachment_ids ) ) );
			if ( $next_gallery !== $current_gallery ) {
				$product->set_gallery_image_ids( $next_gallery );
				$changed = true;
			}
		}
		if ( $changed ) {
			$product->save();
		}
		$this->clear_target_caches( $normalized );
		return [ 'changed' => $changed ];
	}

	/** @return array|\WP_Error */
	public function remove_attachment_from_targets( array $targets, int $attachment_id ) {
		$attachment_id = absint( $attachment_id );
		if ( $attachment_id <= 0 || empty( $targets ) ) {
			return $this->invalid_target();
		}

		$resolved_targets = [];
		foreach ( $targets as $target ) {
			if ( ! is_array( $target ) ) {
				return $this->invalid_target();
			}
			$resolved = $this->resolve_exact_target( $target );
			if ( is_wp_error( $resolved ) ) {
				return $resolved;
			}
			$resolved_targets[] = $resolved;
		}

		$changed = false;
		foreach ( $resolved_targets as $resolved ) {
			$target  = $resolved['target'];
			$product = $resolved['product'];
			$target_changed = false;
			if ( (int) $product->get_image_id( 'edit' ) === $attachment_id ) {
				$product->set_image_id( '' );
				$target_changed = true;
			}
			if ( 'product' === (string) $target['targetType'] ) {
				$current_gallery = array_values( array_filter( array_map( 'absint', (array) $product->get_gallery_image_ids( 'edit' ) ) ) );
				$next_gallery = array_values(
					array_filter(
						$current_gallery,
						static fn( int $id ): bool => $id !== $attachment_id
					)
				);
				if ( $next_gallery !== $current_gallery ) {
					$product->set_gallery_image_ids( $next_gallery );
					$target_changed = true;
				}
			}
			if ( $target_changed ) {
				$product->save();
				$this->clear_target_caches( $target );
				$changed = true;
			}
		}

		return [ 'changed' => $changed ];
	}

	/** @return array{target:array,product:\WC_Product}|\WP_Error */
	private function resolve_exact_target( array $target ) {
		$normalized = Workflow_Item_Identity::normalize_target_snapshot( $target );
		if ( is_wp_error( $normalized ) ) {
			return $normalized;
		}
		if ( ! in_array( $normalized['targetType'], [ 'product', 'variation' ], true ) ) {
			return $this->invalid_target();
		}
		$current = Workflow_Item_Identity::resolve_target( 'product', (int) $normalized['targetId'] );
		if ( is_wp_error( $current ) ) {
			return $current;
		}
		if ( ! Workflow_Item_Identity::hint_matches( $current, Workflow_Item_Identity::target_hint( $normalized ) ) ) {
			return $this->invalid_target();
		}
		$product = wc_get_product( (int) $normalized['targetId'] );
		if ( ! ( $product instanceof \WC_Product ) ) {
			return $this->invalid_target();
		}
		return [ 'target' => $normalized, 'product' => $product ];
	}

	private function clear_target_caches( array $target ): void {
		$this->clear_product_caches( (int) ( $target['targetId'] ?? 0 ) );
		$parent_id = (int) ( $target['parentProductId'] ?? 0 );
		if ( $parent_id > 0 ) {
			$this->clear_product_caches( $parent_id );
		}
	}

	private function invalid_target(): \WP_Error {
		return new \WP_Error(
			'fotogenic_ai_invalid_target_identity',
			__( 'The selected Product target could not be verified.', 'fotogenic-ai' ),
			[ 'status' => 409 ]
		);
	}

	private function clear_product_caches( int $product_id ): void {
		$product_id = absint( $product_id );
		if ( $product_id <= 0 ) {
			return;
		}

		clean_post_cache( $product_id );

		if ( function_exists( 'wc_delete_product_transients' ) ) {
			wc_delete_product_transients( $product_id );
		}

		if ( class_exists( '\WC_Cache_Helper' ) && method_exists( '\WC_Cache_Helper', 'invalidate_cache_group' ) ) {
			\WC_Cache_Helper::invalidate_cache_group( 'product_' . $product_id );
		}

		if ( is_callable( [ '\Iconic_WooThumbs_Cache', 'delete_cache_entries' ] ) ) {
			\Iconic_WooThumbs_Cache::delete_cache_entries( true, $product_id );
		}
	}
}
