<?php

namespace App\Services\Operations;

use App\Models\TransportJob;
use App\Support\Decimal;

final class JobProfitabilityService
{
    public function recalculate(TransportJob $job): TransportJob
    {
        $job->loadMissing(['trips', 'charges', 'costs']);
        $revenue = Decimal::scale('0');
        $cost = Decimal::scale('0');

        foreach ($job->trips as $trip) {
            $revenue = Decimal::add($revenue, (string) $trip->customer_rate, (string) $trip->additional_revenue);
            $cost = Decimal::add($cost, (string) $trip->vendor_rate, (string) $trip->additional_cost);
        }
        foreach ($job->charges as $charge) {
            if ($charge->is_billable) {
                $revenue = Decimal::add($revenue, (string) $charge->amount);
            }
        }
        foreach ($job->costs as $line) {
            $cost = Decimal::add($cost, (string) $line->amount);
        }

        $job->forceFill([
            'number_of_trips' => max(1, $job->trips->count()),
            'actual_revenue' => $revenue,
            'actual_cost' => $cost,
        ])->saveQuietly();

        return $job->refresh();
    }
}
