<?php

namespace App\Modules\Sales\Services;

use App\Modules\Sales\Models\SalesOrder;
use App\Modules\Sales\Models\SalesOrderLine;
use App\Modules\Sales\Repositories\SalesOrderRepository;

final class SalesOrderLifecycleWriter
{
    public function __construct(
        private readonly SalesOrderRepository $orders,
    ) {}

    public function persistAggregatedStatus(SalesOrder $order): void
    {
        $lines = SalesOrderLine::withoutGlobalScopes()
            ->where('tenant_id', (int) $order->tenant_id)
            ->where('sales_order_id', (int) $order->id)
            ->orderBy('id')
            ->get();

        $next = SalesOrderStatusEvaluator::evaluate($lines);
        $order->forceFill(['status' => $next->value]);
        $this->orders->save($order);
    }
}
