<?php

namespace App\Campaigns;

use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Throwable;

class PerformanceDailyHistory
{
    /**
     * Last 30 days for one campaign, oldest first. A date is included when it
     * has a delivery row, a result row, or both.
     *
     * @param  Collection<int, mixed>  $days
     * @param  list<array<string, mixed>>  $outcomes
     * @return array{
     *     from: string,
     *     to: string,
     *     expected_days: int,
     *     days_on_file: int,
     *     rows: list<array<string, mixed>>
     * }
     */
    public static function fromDays(Collection $days, array $outcomes = [], ?int $length = null): array
    {
        $length = max(1, $length ?? PerformanceWindows::AI_CONTEXT_DAYS);
        $to = now()->copy()->startOfDay();
        $from = $to->copy()->subDays($length - 1);
        $fromKey = $from->toDateString();
        $toKey = $to->toDateString();
        $rows = [];

        foreach ($days as $day) {
            if (! $day instanceof PerformanceDay) {
                continue;
            }

            $date = $day->stat_date->toDateString();

            if ($date < $fromKey || $date > $toKey) {
                continue;
            }

            $rows[$date] = self::platformRow($day);
        }

        foreach ($outcomes as $outcome) {
            if (! is_array($outcome)) {
                continue;
            }

            $date = self::dateKey($outcome['date'] ?? null);

            if ($date === null || $date < $fromKey || $date > $toKey) {
                continue;
            }

            $rows[$date] = array_merge($rows[$date] ?? self::emptyPlatform($date), self::outcomeFields($outcome));
        }

        ksort($rows);

        return [
            'from' => $fromKey,
            'to' => $toKey,
            'expected_days' => $length,
            'days_on_file' => count($rows),
            'rows' => array_values($rows),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    private static function platformRow(PerformanceDay $day): array
    {
        $spend = round((float) $day->spend, 2);
        $impressions = (int) $day->impressions;
        $clicks = (int) $day->clicks;

        return [
            'date' => $day->stat_date->toDateString(),
            'platform_row' => true,
            'spend' => $spend,
            'impressions' => $impressions,
            'clicks' => $clicks,
            'cpc' => $day->cpc !== null ? round((float) $day->cpc, 4) : ($clicks > 0 ? round($spend / $clicks, 4) : null),
            'ctr' => $day->ctr !== null ? round((float) $day->ctr, 4) : ($impressions > 0 ? round($clicks / $impressions, 4) : null),
            'conversions' => (int) ($day->conversions ?? 0),
            'conversion_value' => round((float) ($day->conversion_value ?? 0), 2),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    private static function emptyPlatform(string $date): array
    {
        return [
            'date' => $date,
            'platform_row' => false,
            'spend' => null,
            'impressions' => null,
            'clicks' => null,
            'cpc' => null,
            'ctr' => null,
            'conversions' => null,
            'conversion_value' => null,
        ];
    }

    /**
     * @param  array<string, mixed>  $outcome
     * @return array<string, float>
     */
    private static function outcomeFields(array $outcome): array
    {
        $fields = [];

        foreach (['orders', 'revenue', 'roi_conversions', 'installs', 'leads', 'subscriptions', 'bookings'] as $key) {
            if (! array_key_exists($key, $outcome) || ! is_numeric($outcome[$key])) {
                continue;
            }

            $fields[$key] = round((float) $outcome[$key], 4);
        }

        return $fields;
    }

    private static function dateKey(mixed $value): ?string
    {
        if (! is_string($value) || trim($value) === '') {
            return null;
        }

        try {
            return Carbon::parse($value)->toDateString();
        } catch (Throwable) {
            return null;
        }
    }
}
