<?php

namespace App\Console\Commands;

use App\Domains\Tasks\Actions\BuildFollowUpCampaignAudienceAction;
use App\Domains\Tasks\Actions\ExecuteFollowUpCampaignAction;
use App\Domains\Tasks\Models\FollowUpCampaign;
use App\Models\User;
use Illuminate\Console\Command;

class RunScheduledFollowUpCampaignsCommand extends Command
{
    protected $signature = 'followup:run-scheduled-campaigns';

    protected $description = 'Run due follow-up campaigns (auto mode) and keep approval queue up to date';

    public function handle(
        BuildFollowUpCampaignAudienceAction $buildAudience,
        ExecuteFollowUpCampaignAction $executeCampaign
    ): int {
        $processed = 0;
        $queued = 0;

        FollowUpCampaign::query()
            ->where('is_auto_enabled', true)
            ->whereNotNull('next_run_at')
            ->where('next_run_at', '<=', now())
            ->whereIn('status', ['scheduled', 'pending_approval'])
            ->chunk(50, function ($campaigns) use (&$processed, &$queued, $buildAudience, $executeCampaign): void {
                foreach ($campaigns as $campaign) {
                    if ($campaign->requires_approval && ! $campaign->approved_at) {
                        $campaign->update(['status' => 'pending_approval']);
                        $queued++;
                        continue;
                    }

                    /** @var User|null $actor */
                    $actor = User::query()->find($campaign->approved_by ?: $campaign->created_by);
                    if (! $actor) {
                        $campaign->update(['status' => 'failed']);
                        continue;
                    }

                    $filters = is_array($campaign->filters_json) ? $campaign->filters_json : [];
                    $audience = $buildAudience->execute($actor, $filters);
                    $executeCampaign->execute($campaign, $actor, $audience['recipients']);
                    $processed++;
                }
            });

        $this->info("Scheduled campaigns processed: {$processed}. Pending approvals queued: {$queued}.");

        return self::SUCCESS;
    }
}
