<?php

namespace App\Actions;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Shopify\Clients\Graphql;
use stdClass;

class UpdateShopifyVariantCostPriceActionByMaterial
{
    public function __invoke($material, $productId, $price)
    {
        try {



            $shop = env('SHOPIFY_DOMAIN');
            $token = env('SHOPIFY_ACCESS_TOKEN');

            if (!$shop || !$token) {
                Log::error("Shopify domain or access token is not set in environment variables.");
                // Return array format instead of Response object for consistency
                return [
                    'status' => 500,
                    'message' => 'Shopify configuration missing',
                    'data' => null,
                ];
            }

            $client = new Graphql($shop, $token);

            $query = <<<'GRAPHQL'
            query getProductVariants($id: ID!) {
                product(id: $id) {
                    id
                    title
                    variants(first: 200) {
                        edges {
                            node {
                                id
                                title
                                price
                                metafield(namespace: "custom", key: "metal_purity") {
                                        key
                                        value
                                }
                                 inventoryItem {
                                    measurement {
                                         weight {
                                            unit
                                            value
                                        }
                                    }
                                }


                            }
                        }
                    }
                }
            }
        GRAPHQL;


            $variables = [
                'id' =>  $productId,
            ];


            $response = $client->query(["query" => $query, "variables" => $variables]);

            $data = json_decode($response->getBody(), true);

            $productsShop  =  $data['data']['product']['variants']['edges'] ?? [];

            $count_variants_updated = 0; // Count only variants of the specified material that were updated
            $count_variants_matching_material = 0; // Count variants that match the material
            $count_variants_error = 0;
            $product_updated = false; // Track if at least one variant of this product was updated

            foreach ($productsShop as $item) {

                try {
                    $variantId = $item['node']['id'];
                    $weight = $item['node']['inventoryItem']['measurement']['weight']['value'] ?? 0;
                    $metalPurity = strtolower($item['node']['metafield']['value'] ?? '');

                    // Check if variant matches the material
                    if (strpos($metalPurity, strtolower($material)) !== false) {
                        $count_variants_matching_material++;
                        $updatePrice = $price * $weight;
                        if ($updatePrice != $item['node']['price']) {
                            $internal_result = (new UpdateShopifyVariantCostPriceAction())($productId, $variantId, $updatePrice);
                            if ($internal_result) {
                                $count_variants_updated++;
                                $product_updated = true; // Product has at least one variant updated
                            } else {
                                $count_variants_error++;
                                Log::error("Error actualizando precio");
                            }
                        } else {
                            // Price is already the same, count it as updated (no change needed)
                            $count_variants_updated++;
                            $product_updated = true; // Product has at least one variant updated
                        }
                    }

                    //break;
                } catch (\Throwable $th) {
                    Log::error("Error actualizando variante: " . $th->getMessage());
                    $count_variants_error++;
                }
            }

            $result = new stdClass();
            $result->variants_updated = $count_variants_updated; // Real count of updated variants matching material
            $result->variants_matching_material = $count_variants_matching_material; // Total variants matching material
            $result->variant_error = $count_variants_error;
            $result->product_updated = $product_updated ? 1 : 0; // 1 if product was updated (has at least one variant updated), 0 otherwise

            $response = [
                'status' => 200,
                'message' => 'ok',
                'data' => $result,
            ];

            return $response;
        } catch (\Throwable $th) {

            /*Log::error("Failed to update Shopify products variants", [
                'message' => $th->getMessage(),
                'trace' => $th->getTraceAsString(),
            ]);*/

            $response = [
                'status' => 500,
                'message' => $th->getMessage(),
                'data' => null,
            ];

            return $response;
        }
    }
}


