<?php

namespace App\Observers;

use App\Enums\OrderDetailStatus;
use App\Models\Order;
use App\Models\OrderDetail;

class OrderDetailObserver
{
    public function saved(OrderDetail $orderDetail): void
    {
        $this->syncOrderCompletionFlag($orderDetail);
    }

    public function deleted(OrderDetail $orderDetail): void
    {
        $this->syncOrderCompletionFlag($orderDetail);
    }

    private function syncOrderCompletionFlag(OrderDetail $orderDetail): void
    {
        /** @var ?Order $order */
        $order = $orderDetail->order()->first();

        if (! $order) {
            return;
        }

        $terminalStatuses = OrderDetailStatus::terminalValues();
        $totalDetails = $order->details()->count();

        $isComplete = $totalDetails > 0
            && ! $order->details()
                ->where(function ($query) use ($terminalStatuses): void {
                    $query
                        ->whereNull('current_status')
                        ->orWhereNotIn('current_status', $terminalStatuses);
                })
                ->exists();

        if ((bool) $order->Completo_OFP === $isComplete) {
            return;
        }

        $order->forceFill([
            'Completo_OFP' => $isComplete,
        ])->saveQuietly();
    }
}