<?php

namespace App\Console\Commands;

use App\Campaigns\Targeting\TargetingSelections;
use App\Models\Brief;
use App\Models\Campaign;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;

#[Signature('targeting:backfill {--chunk=100 : Records processed per batch}')]
#[Description('Copy legacy country targeting into versioned selections without changing campaigns')]
class BackfillTargetingSelections extends Command
{
    public function handle(TargetingSelections $selections): int
    {
        $chunkSize = max(1, min(1000, (int) $this->option('chunk')));

        Brief::query()->whereNotNull('locations')->chunkById($chunkSize, function ($briefs) use ($selections): void {
            foreach ($briefs as $brief) {
                $selections->backfillBrief($brief);
            }
        });

        Campaign::query()
            ->where(fn ($query) => $query->whereNotNull('locations')->orWhereNotNull('brief_id'))
            ->chunkById($chunkSize, function ($campaigns) use ($selections): void {
                foreach ($campaigns as $campaign) {
                    $selections->backfillCampaign($campaign);
                }
            });

        $this->info('Targeting selections are up to date.');

        return self::SUCCESS;
    }
}
