<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class PostFoodicsDataCommand extends Command
{
    protected $signature = 'foodics:post-data';
    protected $description = 'Fetch data from Foodics API in sequence';

    private $baseUrl;
    private $headers;
    private $endpoints = [
        'create_menu_category',
        'create_ingredient_category',
        'inventory',
        'sub_recipe',
        'recipe',
    ];

    public function __construct()
    {
        parent::__construct();

        $this->baseUrl = env("APP_URL", "http://127.0.0.1:8000") . '/api/foodics/generate-data';
        $this->headers = [
            'Accept' => 'application/json',
            'Content-Type' => 'application/json',
            'X-Custom-Header' => env('MIDDLEWARE_TOKEN', ''),
        ];
    }

    public function handle()
    {
        foreach ($this->endpoints as $type) {

            $url = "{$this->baseUrl}?type={$type}";
            $attempt = 0;
            $maxAttempts = 5;
            $success = false;

            while (!$success && $attempt < $maxAttempts) {
                $attempt++;
                try {
                    $response = Http::withHeaders($this->headers)
                        ->timeout(15)  // Optional: Laravel HTTP timeout (seconds)
                        ->get($url);

                    if ($response->successful()) {
                        Log::channel('foodics')->info("✅ Success: $type on Attempt #$attempt");
                        $success = true;
                    } else {
                        Log::channel('foodics')->warning("⚠️ Failed Attempt #$attempt for $type - Response: " . $response->body());
                        sleep(5); // wait before retry
                    }
                } catch (\Exception $e) {

                    // Special handling for cURL 28 timeout
                    if (strpos($e->getMessage(), 'cURL error 28') !== false) {
                        Log::channel('foodics')->error("❌ Timeout (cURL 28) on $type | Attempt #$attempt. Retrying in 5 sec...");
                    } else {
                        Log::channel('foodics')->error("❌ Exception on $type | Attempt #$attempt: {$e->getMessage()}");
                    }

                    sleep(5);  // wait before retry
                }
            }

            if (!$success) {
                Log::channel('foodics')->critical("💥 Maximum attempts reached for $type. Skipping to next endpoint.");
            } else {
                sleep(5); // wait before moving to the next endpoint
            }
        }
    }
}
