<?php

namespace App\Actions;


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

class UpdateShopifyVariantPriceReferenceAction
{
    public function __invoke($productId, $variantId, $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 response()->json(['error' => 'Shopify configuration missing'], 500);
            }


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

            $query = <<<QUERY
            mutation productVariantsBulkUpdate(\$productId: ID!, \$variants: [ProductVariantsBulkInput!]!) {
                productVariantsBulkUpdate(productId: \$productId, variants: \$variants) {
                product {
                    id
                }
                productVariants {
                    id
                    metafields(first: 2) {
                    edges {
                        node {
                        namespace
                        key
                        value
                        }
                    }
                    }
                }
                userErrors {
                    field
                    message
                }
                }
            }
            QUERY;

            $variables = [
                "productId" => $productId,
                "variants" => [["id" => $variantId, "compareAtPrice" => $price]],
            ];

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


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

            if (
                isset($responseData['data']['productVariantsBulkUpdate']['userErrors'])
                && count($responseData['data']['productVariantsBulkUpdate']['userErrors']) > 0
            ) {
                foreach ($responseData['data']['productVariantsBulkUpdate']['userErrors'] as $error) {
                    Log::error("Error actualizando variante: " . $error['message'], $error['field'] ?? []);
                    return false;
                }
            }

            return true;
        } catch (\Throwable $th) {
            Log::error("Failed to fetch Shopify products", [
                'message' => $th->getMessage(),
                'trace' => $th->getTraceAsString(),
            ]);

            return false;
        }
    }
}
