<?php

namespace App\Campaigns;

class PerformanceWhaleVerdictOverlay
{
    /**
     * @param  array<string, mixed>  $snapshot
     * @return array{0: PerformanceVerdict, 1: string}
     */
    public function apply(array $snapshot, PerformanceVerdict $verdict, string $reason): array
    {
        $affiliate = $snapshot['affiliate'] ?? null;

        if (! is_array($affiliate) || ! ($affiliate['matched'] ?? false)) {
            return [$verdict, $reason];
        }

        $sevenDay = $affiliate['7d'] ?? null;

        if (! is_array($sevenDay)) {
            return [$verdict, $reason];
        }

        $netRevenue = (float) ($sevenDay['net_revenue'] ?? 0);
        $orders = (float) ($sevenDay['orders'] ?? 0);
        $platformSpend = round((float) data_get($snapshot, 'last_7_days.spend', 0), 2);
        $floor = (float) data_get($snapshot, 'rules.zero_click_spend_floor', 10);

        if ($netRevenue > 0 && in_array($verdict, [PerformanceVerdict::Pause, PerformanceVerdict::Stop], true)) {
            return [
                PerformanceVerdict::Continue,
                sprintf(
                    'Platform windows looked weak, but affiliate data shows %s net revenue over 7 days — recommendation: keep running and review.',
                    $this->money($netRevenue),
                ),
            ];
        }

        if ($platformSpend >= $floor
            && $netRevenue <= 0
            && $orders <= 0
            && $verdict === PerformanceVerdict::Continue) {
            return [
                PerformanceVerdict::ActionRequired,
                sprintf(
                    '%s platform spend over 7 days with no affiliate orders or revenue — investigate tracking or landing flow.',
                    $this->money($platformSpend),
                ),
            ];
        }

        return [$verdict, $reason];
    }

    private function money(float $amount): string
    {
        return '$'.number_format($amount, 2);
    }
}
