<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Order\StoreOrderRequest;
use App\Http\Resources\OrderResource;
use App\Models\Order;
use App\Models\Product;
use App\Services\OrderService;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class OrderController extends ApiController
{
    public function __construct(private readonly OrderService $orderService)
    {
    }

    public function index(Request $request): AnonymousResourceCollection
    {
        $orders = Order::query()
            ->with(['items', 'payments.paymentMethod', 'customer'])
            ->where('company_id', $this->currentCompanyId($request))
            ->where('branch_id', $this->currentBranchId($request))
            ->when($request->filled('status'), fn ($query) => $query->where('status', $request->string('status')))
            ->latest('id')
            ->paginate((int) $request->integer('per_page', 15));

        return OrderResource::collection($orders);
    }

    public function store(StoreOrderRequest $request): OrderResource
    {
        $companyId = $this->currentCompanyId($request);

        foreach ($request->input('items', []) as $item) {
            $product = Product::findOrFail($item['product_id']);
            $this->ensureCompanyScoped($product, $companyId);
        }

        $order = $this->orderService->create(
            $this->currentUser($request),
            $companyId,
            $this->currentBranchId($request),
            $request->validated(),
        );

        return new OrderResource($order);
    }
}
