<?php

namespace App\Library\CampaignDecision;

class CampaignMetricsCalculator
{
    /**
     * @return array{
     *     spend: float,
     *     impressions: int,
     *     clicks: int,
     *     cpc: ?float,
     *     ctr: ?float,
     *     orders: float,
     *     revenue: float,
     *     cvr: ?float,
     *     cpa: ?float,
     *     roas: ?float
     * }
     */
    public static function fromTotals(
        float $spend,
        int $impressions,
        int $clicks,
        float $orders = 0,
        float $revenue = 0,
    ): array {
        $spend = round($spend, 2);

        return [
            'spend' => $spend,
            'impressions' => $impressions,
            'clicks' => $clicks,
            'cpc' => $clicks > 0 ? round($spend / $clicks, 4) : null,
            'ctr' => $impressions > 0 ? round($clicks / $impressions, 4) : null,
            'orders' => round($orders, 4),
            'revenue' => round($revenue, 2),
            'cvr' => $clicks > 0 ? round($orders / $clicks, 4) : null,
            'cpa' => $orders > 0 ? round($spend / $orders, 2) : null,
            'roas' => $spend > 0 && $revenue > 0 ? round($revenue / $spend, 4) : null,
        ];
    }

    public static function percentChange(?float $current, ?float $previous): ?float
    {
        if ($current === null || $previous === null || abs($previous) < 0.0001) {
            return null;
        }

        return round((($current - $previous) / $previous) * 100, 2);
    }

    public static function trendStatus(?float $percentChange): string
    {
        if ($percentChange === null) {
            return 'STABLE';
        }

        if ($percentChange <= -25) {
            return 'STRONG_NEGATIVE';
        }

        if ($percentChange < -5) {
            return 'NEGATIVE';
        }

        if ($percentChange >= 25) {
            return 'STRONG_POSITIVE';
        }

        if ($percentChange > 5) {
            return 'POSITIVE';
        }

        return 'STABLE';
    }
}
