<?php

namespace Inside\DESK\Console;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Queue;
use Inside\Content\Models\Contents\Alerts;
use Inside\Content\Models\Contents\Users;
use Inside\DESK\Jobs\SendAlert;
use Inside\LHG\Facades\RightApi;

class SendAlerts extends Command
{
    /**
     * @var string
     */
    protected $name = 'desk:send-alerts';

    /*
   * @var string
   */
    protected $signature = 'desk:send-alerts {--batchsize=}';

    /**
     * @var string
     */
    protected $description = 'Send alerts';

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Import users
     */
    public function handle(): void
    {
        if (DB::table('desk_alerts_to_send')->count() === 0) {
            return;
        }

        $alertsToSend = DB::table('desk_alerts_to_send')->get();
        foreach ($alertsToSend as $alert) {
            $content = Alerts::query()->find($alert->uuid);

            if (!$content) {
                DB::table('desk_alerts_to_send')->where('uuid', $alert->uuid)->delete();
                DB::table('desk_alerts_sent')->where('uuid', $alert->uuid)->delete();
                continue;
            }

            $query = Users::query()->where('langcode', $content->langcode)->where('status', 1);

            $users = $query->get();

            $fields = [
                'brands',
                'countries',
                'management_modes',
                'profiles',
            ];

            foreach ($fields as $field) {
                $alias = 'pivots' . studly_case($field);
                $uuids = $content->{camel_case($field)}->pluck('uuid')->toArray();

                $query->select('inside_content_users.*')->join('inside_pivots AS ' . $alias, function ($join) use ($alias, $uuids) {
                    $join->on($alias . '.parent_uuid', '=', 'inside_content_users.uuid')
                        ->where(function ($subQuery) use ($alias, $uuids) {
                            $subQuery->whereIn($alias . '.related_uuid', $uuids);
                        });
                })->groupBy('inside_content_users.uuid');
            }

            $batchSize = (int) $this->option('batchsize');

            $alreadySent = DB::table('desk_alerts_sent')->where('uuid', $alert->uuid)->pluck('user_uuid')->toArray();
            $chunks = array_chunk($alreadySent, 300);

            foreach ($chunks as $chunk) {
                $query->whereNotIn('inside_content_users.uuid', $chunk);
            }

            if ($batchSize && $batchSize > -1) {
                $query->limit($batchSize);
            }


            $notifialedUsers = RightApi::getNotifiableUsers(RightApi::NOTIFICATION);
            if ($notifialedUsers->isEmpty()) {
                Log::info("No users to send newsletter");
                return;
            }

            $users = $query->get();

            if ($users->count() === 0) {
                DB::table('desk_alerts_to_send')->where('uuid', $alert->uuid)->delete();
                DB::table('desk_alerts_sent')->where('uuid', $alert->uuid)->delete();
                continue;
            }
            $users = $users->filter(fn ($user) => $notifialedUsers->has($user->email));

            foreach ($users as $user) {
                Queue::push(new SendAlert($user, $content), '', env('DESK_ALERTS_QUEUE', 'desk_alerts'));
            }
        }
    }
}
