<?php

namespace App\Modules\Inventory\Services;

use App\Modules\Inventory\Models\Product;
use App\Modules\Inventory\Models\Category;
use App\Modules\Inventory\Models\Unit;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ProductService
{
    /**
     * Upsert product from external POS source.
     *
     * @param array $data
     * @return Product
     */
    public function upsertFromPos(array $data)
    {
        return DB::transaction(function () use ($data) {
            $externalId = $data['external_pos_id'] ?? null;

            if (!$externalId) {
                throw new \Exception("External POS ID is required for syncing.");
            }

            // Try to find by external_pos_id
            $product = Product::where('external_pos_id', $externalId)->first();

            if (!$product) {
                // If not found, create new
                // Optional: Check SKU conflict if needed, but for now trust POS ID
                $product = new Product();
                $product->external_pos_id = $externalId;
            }

            // Map allowed fields
            $product->name = $data['name'];
            $product->barcode = $data['barcode'] ?? $product->barcode;
            $product->price = $data['price'] ?? 0;
            
            // Generate Code if missing (use code or external_id)
            if (empty($product->code)) {
                $product->code = $data['code'] ?? $product->external_pos_id;
            }
            
            // Handle Category (Default: 未分類)
            if (empty($product->category_id)) {
                $categoryName = $data['category'] ?? '未分類';
                $category = Category::firstOrCreate(
                    ['name' => $categoryName],
                    ['code' => 'CAT-' . strtoupper(bin2hex(random_bytes(4)))]
                );
                $product->category_id = $category->id;
            }

            // Handle Base Unit (Default: 個)
            if (empty($product->base_unit_id)) {
                $unitName = $data['unit'] ?? '個';
                $unit = Unit::firstOrCreate(['name' => $unitName]);
                $product->base_unit_id = $unit->id;
            }
            
            $product->is_active = $data['is_active'] ?? true;
            
            $product->save();

            return $product;
        });
    }
}
