<?php

namespace App\Modules\Sales\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Sales\Models\SalesOrder;
use App\Modules\Sales\Repositories\SalesOrderRepository;
use App\Modules\Sales\Services\SalesOrderStockHintLookup;
use App\Modules\Sales\Support\SalesOrderLifecycleStatus;
use App\Support\Operational\SalesOrderOperationalPresenter;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\View\View;

class SalesOrderPageController extends Controller
{
    public function __construct(
        private readonly SalesOrderRepository $orders,
        private readonly SalesOrderStockHintLookup $stockHints,
    ) {}

    public function index(Request $request): View
    {
        $this->authorize('viewAny', SalesOrder::class);
        $status = $request->query('status');
        $viewFocus = $request->query('view');

        return view('pages.sales.orders.index', [
            'orders' => $this->orders->paginateOperationalIndex(
                is_string($status) && $status !== '' ? $status : null,
                is_string($viewFocus) && $viewFocus !== '' ? $viewFocus : null,
            ),
            'statusFilter' => is_string($status) ? $status : null,
            'viewFocus' => is_string($viewFocus) ? $viewFocus : null,
            'statusChoices' => SalesOrderLifecycleStatus::cases(),
        ]);
    }

    public function show(Request $request, SalesOrder $salesOrder): View
    {
        $this->authorize('view', $salesOrder);
        $salesOrder->load([
            'lines' => static fn ($q) => $q->orderBy('line_position')->orderBy('id'),
            'lines.inventoryItem',
            'lines.warehouse',
            'returns' => static fn ($q) => $q->orderByDesc('id'),
        ]);
        $tenantId = (int) $request->user()->tenant_id;
        $hints = $this->stockHints->availableByWarehouseItem($tenantId, $salesOrder->lines);
        $operational = app(SalesOrderOperationalPresenter::class)->detail($salesOrder);

        return view('pages.sales.orders.show', [
            'order' => $salesOrder,
            'stockHints' => $hints,
            'operationBatchId' => (string) Str::uuid(),
            ...$operational,
        ]);
    }
}
