<?php

namespace App\Actions;

use App\Constants\Roles;
use App\Models\CanceledTrip;
use App\Models\Performance as ModelsPerformance;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Shopify\Clients\Graphql;
use stdClass;

class ListShopifyProductsAction
{
    public function __invoke()
    {
        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 = <<<'GRAPHQL'
            {
                products(first: 100, query: "(status:ACTIVE) AND (title:'10k Gold Semi Solid Miami Cuban Link Chain (Copy for testing)' OR title:'10k Gold Semi Solid Miami Cuban Link Chain (Copy for testing)')") {
                    edges {
                        node {
                            id
                            title
                            handle
                        }
                        cursor
                    }
                    pageInfo {
                        hasNextPage
                    }
                }
            }
            GRAPHQL;

            $response = $client->query($query);
            $data = json_decode($response->getBody(), true);
            $productsShop  =  $data['data']['products']['edges'] ?? [];
            $products = [];
            foreach ($productsShop as $item) {
                $product = new stdClass();
                $product->id = $item['node']['id'];
                $product->title = $item['node']['title'];
                $products[] = $product;
            }

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

            throw new \RuntimeException("An error occurred while fetching Shopify products.");
        }
    }
}
