<?php

namespace App\Services\Meta;

class MetaAdsMetricsCalculator
{
    public function calculate(
        float $spend,
        float $purchaseValue,
        float $attributedOrderValue,
        float $deliveredRevenue,
        float $returnedValue,
        float $cancelledValue,
        int $deliveredOrders,
        int $returnedOrders,
        float $profit
    ): array {
        $finalOrders = $deliveredOrders + $returnedOrders;
        $returnAdjustedRevenue = max($attributedOrderValue - $returnedValue - $cancelledValue, 0);

        return [
            'purchase_roas' => $this->ratio($purchaseValue, $spend),
            'delivered_roas' => $this->ratio($deliveredRevenue, $spend),
            'return_adjusted_roas' => $this->ratio($returnAdjustedRevenue, $spend),
            'cost_per_delivered_order' => $deliveredOrders > 0
                ? round($spend / $deliveredOrders, 4)
                : null,
            'profit_roas' => $this->ratio($profit, $spend),
            'return_rate' => $finalOrders > 0
                ? round(($returnedOrders / $finalOrders) * 100, 2)
                : 0.0,
        ];
    }

    private function ratio(float $value, float $spend): ?float
    {
        return $spend > 0 ? round($value / $spend, 4) : null;
    }
}
