<?php

namespace App\Http\Controllers\Api\Catalog;

use App\Domains\Catalog\Models\Product;
use App\Domains\Catalog\Models\ProductStockMovement;
use App\Http\Controllers\Controller;
use App\Http\Requests\Catalog\StoreProductRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

class ProductStoreController extends Controller
{
    public function __invoke(StoreProductRequest $request): JsonResponse
    {
        $product = DB::transaction(function () use ($request) {
            $data = $request->validated();
            $tracked = $data['stock_mode'] === 'tracked';
            $stockQuantity = (int) ($data['stock_quantity'] ?? 0);
            $initialStock = (int) ($data['initial_stock_quantity'] ?? $stockQuantity);

            $product = Product::query()->create([
                ...$data,
                'tenant_id' => $request->user()->tenant_id,
                'currency_code' => strtoupper($request->validated('currency_code')),
                'initial_stock_quantity' => $tracked ? $initialStock : 0,
                'stock_quantity' => $tracked ? $stockQuantity : 0,
                'availability_status' => $tracked
                    ? ($stockQuantity > 0 ? 'available' : 'out_of_stock')
                    : ($data['availability_status'] ?? 'available'),
            ]);

            if ($tracked && $stockQuantity > 0) {
                ProductStockMovement::query()->create([
                    'tenant_id' => $request->user()->tenant_id,
                    'product_id' => $product->id,
                    'movement_type' => 'initial',
                    'quantity_before' => 0,
                    'quantity_change' => $stockQuantity,
                    'quantity_after' => $stockQuantity,
                    'notes' => 'Initial stock at product creation',
                    'created_by' => $request->user()->id,
                ]);
            }

            return $product;
        });

        return response()->json(['data' => $product->fresh('category')], 201);
    }
}
