<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Repositories\AssetRepository;
use App\Services\Slack\SlackMessageHelperService;
use App\Services\Slack\SlackService;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Notify the user about loaner item due next week.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(protected SlackService $slackService, protected SlackMessageHelperService $slackMessageHelperService, protected AssetRepository $assetRepository)
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $assets = $this->assetRepository->getLoanerDueNextWeekAssets()->get();

        if (count($assets) === 0) {
            return $this->info("No loaned assets are due next week.");
        }

        $userWiseAssets = $assets->groupBy('user_id');

        foreach ($userWiseAssets as $assets) {

            $chunkSize = 50;
            // Chunk the data into smaller groups as slack message size is limited.
            $assetChunks = $assets->chunk($chunkSize);
            foreach ($assetChunks as $chunk) {
                $message = $this->slackMessageHelperService->getLoanerDueNextWeekUserMessage($chunk);

                $this->slackService->sendMessageToUser(optional($chunk[0]->user)->email, $message, 'loaner_asset_due_next_week_user_notification');
            }
        }

        return $this->info('Notifications send successfully.');
    }
}
