<?php

namespace App\Console\Commands\Mock;

use App\Packages\Capsule\Models\Capsule;
use App\Packages\Capsule\Models\CapsuleComment;
use App\Packages\User\Models\User;
use Illuminate\Console\Command;

class MockCommentCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mock:comment';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create mock comments';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $users = User::repository()->getRegisteredUsers();

        if ( ! $users ) {
            $this->info('No registered users');
            return false;
        }

        $capsules = Capsule::repository()->all();

        if ( ! $capsules ) {
            $this->info('No capsules');
            return false;
        }

        $max_comments = (int) $this->ask('Max comments per capsule')?:20;

        $status_bar = $this->output->createProgressBar($capsules->count());
        $status_bar->start();

        foreach ($capsules as $capsule) {
            factory(CapsuleComment::class, rand(0, $max_comments))
                ->create()->each(function (CapsuleComment $comment) use ($users, $capsule) {
                    $user = $users->random();

                    $comment->user_id = $user->id;
                    $comment->capsule_id = $capsule->id;
                    $comment->save();

                    $user->refreshCommentCount();
                });

            /** Refresh capsule total comments */
            $capsule->refreshCommentCount();

            $status_bar->advance();
        }

        $status_bar->finish();
        $this->info('');
    }
}
