<?php

namespace App\Console\Commands;

use App\Campaigns\CampaignPerformanceMapper;
use App\Campaigns\CampaignPerformanceSync;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;

#[Signature('campaigns:sync-performance {--platform= : meta or google} {--campaign= : external campaign id} {--limit= : max campaigns} {--dump : dump stats} {--map : map stats to suggestions} {--hourly : hourly ingest (lifetime backfill, then 3h refresh)}')]
#[Description('Dump campaign performance and map it into pending suggestions')]
class SyncCampaignPerformanceCommand extends Command
{
    public function handle(CampaignPerformanceSync $sync, CampaignPerformanceMapper $mapper): int
    {
        $hourly = (bool) $this->option('hourly');
        $dump = $this->option('dump') || ! $this->option('map');
        $map = $this->option('map') || ! $this->option('dump');

        $platform = $this->option('platform') !== null && $this->option('platform') !== ''
            ? (string) $this->option('platform')
            : null;
        $campaign = $this->option('campaign') !== null && $this->option('campaign') !== ''
            ? (string) $this->option('campaign')
            : null;
        $limit = $this->option('limit');
        $limit = is_numeric($limit) ? (int) $limit : null;

        if ($dump) {
            $result = $hourly
                ? $sync->runHourly($platform, $campaign, $limit)
                : $sync->run($platform, $campaign, $limit);
            $this->components->info(sprintf(
                'Performance %s dump attempted %d campaign(s): %d dumped, %d failed.',
                $hourly ? 'hourly' : 'daily',
                $result['attempted'],
                $result['dumped'],
                $result['failed'],
            ));

            foreach ($result['errors'] ?? [] as $error) {
                $this->components->error($error);
            }
        }

        if ($map) {
            $runType = $hourly ? 'hourly' : 'daily';
            $result = $mapper->run($platform, $campaign, $limit, $runType);
            $this->components->info(sprintf(
                'Performance map (%s) attempted %d campaign(s): %d mapped, %d failed.',
                $runType,
                $result['attempted'],
                $result['mapped'],
                $result['failed'],
            ));
        }

        return self::SUCCESS;
    }
}
