<?php

namespace App\Modules\Integration\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Modules\Inventory\Services\ProductService;
use Illuminate\Support\Facades\Log;

class ProductSyncController extends Controller
{
    protected $productService;

    public function __construct(ProductService $productService)
    {
        $this->productService = $productService;
    }

    public function upsert(Request $request)
    {
        $request->validate([
            'external_pos_id' => 'required|string',
            'name' => 'required|string',
            'price' => 'nullable|numeric',
            'barcode' => 'nullable|string',
            'category' => 'nullable|string',
            'unit' => 'nullable|string',
            'updated_at' => 'nullable|date',
        ]);

        try {
            $product = $this->productService->upsertFromPos($request->all());

            return response()->json([
                'message' => 'Product synced successfully',
                'data' => [
                    'id' => $product->id,
                    'external_pos_id' => $product->external_pos_id,
                ]
            ]);
        } catch (\Exception $e) {
            Log::error('Product Sync Failed', ['error' => $e->getMessage(), 'payload' => $request->all()]);
            return response()->json(['message' => 'Sync failed'], 500);
        }
    }
}
