<?php

declare(strict_types=1);

namespace App\Services\Order;

use App\Events\Ecommerce\Product\Order\OrderCreated;
use App\Models\Ecommerce\Product\Order\Order;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class CreateOrderService
{
    /**
     * Create a new order for the user
     */
    public function execute(User $user, array $data): Order
    {
        return DB::transaction(function () use ($user, $data) {
            // 1. Create the order
            $order = Order::create($data);

            // 2. Process Cart Items
            $user->carts()
                ->with(['product' => function ($query) {
                    $query->with(['media', 'channels']);
                }])
                ->get()
                ->each(function ($cart) use ($order) {
                    // Create Order Item
                    DB::table('order_items')->insert([
                        'product_name' => $cart->product->name,
                        'product_id' => $cart->product_id,
                        'order_id' => $order->id,
                        'channel_id' => $cart->product->channels->first()?->id ?? tmpostChannel()->id,
                        'quantity' => $cart->product_quantity,
                        'unit_price_amount' => $cart->product->price_amount,
                        'unit_cost_amount' => $cart->product->cost_amount,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);

                    // Update Stock directly in products table, also relationship
                    $stock = $cart->product->stock - $cart->product_quantity;
                    $cart->product->update([
                        'stock' => $stock,
                    ]);

                    $data = DB::table('inventory_product')->where('product_id', $cart->product_id)->first();
                    if ($data) {
                        DB::table('inventory_product')->where('id', $data->id)->update([
                            'stock' => $stock,
                        ]);
                    } else {
                       warn('Product has no inventory record', json_encode([
                        'product_id' => $cart->product_id,
                        'order_id' => $order->id,
                       ]));
                    }

                });

            // 3. Clear User Cart
            $user->carts()->delete();

            // 4. Dispatch Event
            OrderCreated::dispatch($order);

            return $order;
        });
    }
}
