<?php

namespace App\Console\Commands;

use App\Campaigns\CampaignReviewDetailBackfill;
use App\Models\CampaignDecision;
use App\Models\CampaignPerformanceSuggestion;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

#[Signature('campaigns:backfill-review-details {--campaign= : Only this platform campaign id} {--dry-run : Report rows that would change without writing}')]
#[Description('Fill creative ids, image prompts, and landing-page prompts on stored reviews')]
class BackfillReviewDetailsCommand extends Command
{
    public function handle(CampaignReviewDetailBackfill $backfill): int
    {
        $campaign = trim((string) $this->option('campaign'));
        $dryRun = (bool) $this->option('dry-run');
        $suggestions = $this->walk(
            CampaignPerformanceSuggestion::query()->when($campaign !== '', fn (Builder $query) => $query->where('external_campaign_id', $campaign)),
            'snapshot',
            $backfill,
            $dryRun,
        );
        $decisions = $this->walk(
            CampaignDecision::query()->when($campaign !== '', fn (Builder $query) => $query->where('external_campaign_id', $campaign)),
            'snapshot_json',
            $backfill,
            $dryRun,
        );

        $verb = $dryRun ? 'Would update' : 'Updated';
        $this->components->info(sprintf(
            '%s %d suggestion(s) and %d decision(s).',
            $verb,
            $suggestions,
            $decisions,
        ));

        return self::SUCCESS;
    }

    /**
     * @param  Builder<Model>  $query
     */
    private function walk(Builder $query, string $column, CampaignReviewDetailBackfill $backfill, bool $dryRun): int
    {
        $updated = 0;

        $query->orderBy('id')->chunkById(200, function ($rows) use ($column, $backfill, $dryRun, &$updated): void {
            foreach ($rows as $row) {
                $snapshot = $row->getAttribute($column);

                if (! is_array($snapshot)) {
                    continue;
                }

                $next = $backfill->apply($snapshot);

                if ($next === null) {
                    continue;
                }

                $updated++;

                if ($dryRun) {
                    continue;
                }

                $row->setAttribute($column, $next);
                $row->save();
            }
        });

        return $updated;
    }
}
