<?php

namespace App\Services;

use App\Models\Address;
use App\Models\Order;
use App\Models\OrderItem;
use Illuminate\Support\Facades\DB;

class OrderService
{
    public function createFromCart(int $userId, int $addressId): Order
    {
        $user = \App\Models\User::findOrFail($userId);
        $address = Address::where('user_id', $userId)->findOrFail($addressId);
        $cartItems = $user->cartItems()->with('product')->get();

        if ($cartItems->isEmpty()) {
            throw new \InvalidArgumentException(__('Cart is empty.'));
        }

        return DB::transaction(function () use ($user, $address, $cartItems) {
            $order = new Order;
            $order->number = Order::generateNumber();
            $order->user_id = $user->id;
            $order->address_id = $address->id;
            $order->subtotal = 0;
            $order->delivery_fee = 0;
            $order->total = 0;
            $order->status = Order::STATUS_PENDING;
            $order->payment_status = Order::PAYMENT_PENDING;
            $order->save();

            $subtotal = 0;
            foreach ($cartItems as $cartItem) {
                $product = $cartItem->product;
                $unitPrice = (float) $product->price;
                $qty = $cartItem->quantity;
                $total = round($unitPrice * $qty, 2);
                $subtotal += $total;
                OrderItem::create([
                    'order_id' => $order->id,
                    'product_id' => $product->id,
                    'product_name' => $product->name,
                    'unit_price' => $unitPrice,
                    'quantity' => $qty,
                    'total' => $total,
                ]);
            }
            $order->subtotal = round($subtotal, 2);
            $order->total = $order->subtotal + (float) $order->delivery_fee;
            $order->save();

            $user->cartItems()->delete();

            return $order->load('items', 'address');
        });
    }
}
