<?php

namespace App\Console\Commands;

use App\Models\Post;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

/**
 * Publishes posts whose publish_at timestamp has passed.
 * Scheduled every minute via console/kernel.
 */
class PublishScheduledPostsCommand extends Command
{
    protected $signature   = 'posts:publish-scheduled';
    protected $description = 'Publish all scheduled posts whose publish_at time has been reached.';

    public function handle(): int
    {
        $count = Post::where('status', Post::STATUS_SCHEDULED)
            ->where('publish_at', '<=', now())
            ->count();

        if ($count === 0) {
            $this->line('No scheduled posts to publish.');
            return self::SUCCESS;
        }

        $published = 0;

        Post::where('status', Post::STATUS_SCHEDULED)
            ->where('publish_at', '<=', now())
            ->chunkById(100, function ($posts) use (&$published) {
                foreach ($posts as $post) {
                    DB::transaction(function () use ($post) {
                        $post->update(['status' => Post::STATUS_PUBLISHED]);
                    });
                    $published++;
                }
            });

        $this->info("Published {$published} scheduled post(s).");

        return self::SUCCESS;
    }
}
