<?php

namespace App\Modules\Integration\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Modules\Inventory\Contracts\ProductServiceInterface;
use Illuminate\Support\Facades\Log;

class ProductSyncController extends Controller
{
    protected $productService;

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

    public function upsert(Request $request)
    {
        $request->validate([
            'external_pos_id' => 'required|string|max:255',
            'name' => 'required|string|max:255',
            'price' => 'nullable|numeric|min:0|max:99999999.99',
            'barcode' => 'nullable|string|max:100',
            'category' => 'nullable|string|max:100',
            'unit' => 'nullable|string|max:100',
            'brand' => 'nullable|string|max:100',
            'specification' => 'nullable|string|max:255',
            'cost_price' => 'nullable|numeric|min:0|max:99999999.99',
            'member_price' => 'nullable|numeric|min:0|max:99999999.99',
            'wholesale_price' => 'nullable|numeric|min:0|max:99999999.99',
            '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: ' . $e->getMessage(),
            ], 500);
        }
    }
}
