<?php

namespace App\Library\CampaignDecision;

class CampaignDecisionReasonFormatter
{
    /**
     * @param  array<string, mixed>  $row
     */
    public static function line(array $row): string
    {
        if (is_string($row['message'] ?? null) && $row['message'] !== '') {
            return $row['message'];
        }

        $metric = (string) ($row['metric'] ?? 'rule');
        $channel = (string) ($row['channel'] ?? '');
        $impact = (string) ($row['impact'] ?? '');
        $detail = (string) ($row['detail'] ?? '');

        $label = match ($metric) {
            'hour_spend_no_clicks' => 'Hour window: spend with no clicks',
            'learning_period' => 'Still in learning period',
            'platform_sync' => 'Platform ingest sync failed',
            'platform_metrics' => 'No platform metrics in Whale',
            'lagged_roas' => 'Lagged affiliate ROAS',
            'lagged_cpa' => 'Lagged affiliate CPA',
            'hour_channel' => 'Hour channel signal',
            default => str_replace('_', ' ', ucfirst($metric)),
        };

        $parts = array_filter([$label, $channel !== '' ? "({$channel})" : null, $impact !== '' ? $impact : null]);

        $line = implode(' ', $parts);

        if ($detail !== '') {
            $line .= ' — '.$detail;
        }

        if (isset($row['current'], $row['target'])) {
            $line .= sprintf(' — %s vs target %s', $row['current'], $row['target']);
        }

        return $line;
    }
}
