<?php

namespace App\Console\Commands;

use App\Campaigns\CampaignPerformanceAdopsMonitor;
use App\Models\CampaignPerformanceSuggestion;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;

#[Signature('campaigns:backfill-reviews {--platform=meta : meta, google, or linkedin} {--campaign= : platform campaign id} {--limit= : max campaigns, 0 for all}')]
#[Description('Rebuild Whale campaign reviews and store the full recommendation on each suggestion row')]
class BackfillCampaignReviewsCommand extends Command
{
    public function handle(CampaignPerformanceAdopsMonitor $monitor): int
    {
        $platform = $this->option('platform') !== null && $this->option('platform') !== ''
            ? (string) $this->option('platform')
            : 'meta';
        $campaign = $this->option('campaign') !== null && $this->option('campaign') !== ''
            ? (string) $this->option('campaign')
            : null;
        $limit = $this->option('limit');
        $limit = is_numeric($limit) ? (int) $limit : null;

        $result = $monitor->run($platform, $campaign, $limit, 'hourly');

        if ($result['skipped'] !== null) {
            $this->components->warn('Review backfill skipped: '.$result['skipped']);

            return self::SUCCESS;
        }

        $stored = 0;

        foreach ($result['results'] as $row) {
            $suggestion = CampaignPerformanceSuggestion::query()
                ->where('platform', $row['platform'])
                ->where('external_campaign_id', $row['campaign_id'])
                ->first();
            $analysis = trim((string) data_get($suggestion?->snapshot, 'review.analysis', ''));

            $this->newLine();
            $this->line($row['campaign_id'].' · '.($row['name'] ?? ''));

            if ($analysis !== '') {
                $stored++;
                $this->line($analysis);

                continue;
            }

            $error = trim((string) ($suggestion?->last_error ?? ''));
            $this->components->warn($error !== '' ? $error : 'No full recommendation was stored. The rules plan was kept.');
        }

        $this->newLine();
        $this->components->info(sprintf(
            'Stored a full recommendation on %d of %d campaign(s). %d failed to map.',
            $stored,
            $result['attempted'],
            $result['failed'],
        ));

        return $result['failed'] > 0 ? self::FAILURE : self::SUCCESS;
    }
}
