<?php

namespace App\Http\Controllers\Api\Jumpseller;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Http;
use App\Models\Order;
use Illuminate\Http\Request;

class OrdersController extends Controller
{
    /**
     * Sincroniza pedidos desde Jumpseller y los guarda en la base de datos local.
     */
    public function sync()
    {
        try {
            // 1️⃣ Llamada al endpoint de Jumpseller
            $response = Http::acceptJson()
                ->timeout(15)
                ->retry(2, 500)
                ->withHeaders(['User-Agent' => 'Radar-API/1.0'])
                ->get('https://api.jumpseller.com/v1/orders.json', [
                    'login'     => config('services.jumpseller.login'),
                    'authtoken' => config('services.jumpseller.auth_token'),
                    'limit'     => 50,
                ]);

            if (!$response->successful()) {
                return response()->json([
                    'error' => 'Jumpseller',
                    'status' => $response->status(),
                    'body' => $response->json(),
                ], $response->status());
            }

            $data = $response->json();

            // 2️⃣ Procesar cada pedido
            $saved = 0;
            foreach ($data as $item) {
                $order = $item['order'] ?? null;
                if (!$order) continue;

                Order::updateOrCreate(
                    ['order_id' => $order['id']],
                    [
                        'campaign_id'     => 'GoPoints',
                        'customer_name'   => $order['billing_address']['name'] ?? null,
                        'customer_email'  => $order['customer']['email'] ?? null,
                        'status'          => $order['status'] ?? 'pending',
                        'total'           => $order['total'] ?? 0,
                        'discount'        => $order['discount'] ?? 0,
                        'shipping'        => $order['shipping'] ?? 0,
                        'payment_method'  => $order['payment_method_name'] ?? null,
                        'products'        => $order['products'] ?? [],
                        'shipping_address'=> $order['shipping_address'] ?? [],
                    ]
                );

                $saved++;
            }

            return response()->json([
                'message' => 'Pedidos sincronizados correctamente',
                'total_saved' => $saved,
            ], 200);

        } catch (\Throwable $e) {
            return response()->json([
                'error' => 'Error al sincronizar pedidos',
                'message' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Muestra los pedidos almacenados.
     */
    public function index()
    {
        return response()->json(Order::latest()->get());
    }
}
