<?php

namespace App\Console\Commands;

use App\Campaigns\Manager\CampaignSynchronizer;
use App\Campaigns\Manager\ManagedCampaigns;
use App\Models\Campaign;
use App\Models\CampaignSyncRun;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Throwable;

#[Signature('campaigns:sync-structure {--campaign=* : local campaign id(s) to read regardless of age} {--limit= : most campaigns to read} {--stale= : minutes after which a snapshot is read again}')]
#[Description('Read managed campaigns from their platforms and record what changed (read-only towards the platforms)')]
class SyncCampaignStructures extends Command
{
    public function handle(CampaignSynchronizer $synchronizer): int
    {
        $ids = array_filter(array_map(intval(...), (array) $this->option('campaign')));
        $limit = is_numeric($this->option('limit')) ? max(1, (int) $this->option('limit')) : (int) config('campaign-manager.sync_batch_size', 25);
        $stale = is_numeric($this->option('stale')) ? max(0, (int) $this->option('stale')) : (int) config('campaign-manager.stale_after_minutes', 60);

        $campaigns = ManagedCampaigns::query()
            ->when($ids !== [], fn ($query) => $query->whereKey($ids))
            ->when($ids === [], fn ($query) => $query
                ->whereDoesntHave('syncRuns', fn ($runs) => $runs->where('started_at', '>=', now()->subMinutes($stale)))
                ->withMax('syncRuns', 'started_at')
                ->orderBy('sync_runs_max_started_at')
                ->limit($limit))
            ->get();

        if ($campaigns->isEmpty()) {
            $this->components->info('No managed campaigns need reading.');

            return self::SUCCESS;
        }

        $failed = 0;

        foreach ($campaigns as $campaign) {
            /** @var Campaign $campaign */
            $label = sprintf('#%d %s %s', $campaign->id, $campaign->platform, $campaign->external_campaign_id);

            try {
                $run = $synchronizer->sync($campaign, 'scheduled', 'system campaign manager sync');
            } catch (Throwable $exception) {
                $failed++;
                $this->components->error($label.': '.$exception->getMessage());

                continue;
            }

            if ($run->status === CampaignSyncRun::Failed) {
                $failed++;
                $this->components->error($label.': '.$run->error);

                continue;
            }

            $this->components->twoColumnDetail($label, sprintf('%s, %d objects, %d changes', $run->status, $run->entity_count, $run->drift_count));
        }

        $this->components->info(sprintf('Read %d campaign(s), %d failed.', $campaigns->count(), $failed));

        return $failed === 0 ? self::SUCCESS : self::FAILURE;
    }
}
