<?php

namespace App\Console\Commands;

use App\Jobs\SendWebPushToUser;
use App\Models\Partnership;
use App\Models\User;
use App\Models\WorkspaceMember;
use App\Queries\PartnershipsNeedingReminder;
use App\Services\WebPushSender;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;

class CollabsPushRemindersCommand extends Command
{
    protected $signature = 'collabs:push-reminders';

    protected $description = 'Queue web push reminders for upcoming collabs with a scheduled date on or before today';

    public function handle(WebPushSender $sender): int
    {
        if (! $sender->isConfigured()) {
            $this->warn('VAPID keys are not configured; skipping.');

            return self::SUCCESS;
        }

        $queued = 0;

        PartnershipsNeedingReminder::query()->chunkById(50, function ($partnerships) use (&$queued): void {
            foreach ($partnerships as $partnership) {
                /** @var Partnership $partnership */
                $memberIds = WorkspaceMember::query()
                    ->where('workspace_id', $partnership->workspace_id)
                    ->pluck('user_id')
                    ->unique();

                foreach ($memberIds as $userId) {
                    $user = User::query()->find($userId);
                    if ($user === null || ! $partnership->isVisibleTo($user)) {
                        continue;
                    }
                    if ($user->pushSubscriptions()->doesntExist()) {
                        continue;
                    }

                    $cacheKey = sprintf('push-reminder:%d:%d:%s', $userId, $partnership->id, now()->toDateString());
                    if (! Cache::add($cacheKey, true, now()->endOfDay())) {
                        continue;
                    }

                    SendWebPushToUser::dispatch(
                        (int) $userId,
                        (string) config('app.name', 'Collabs'),
                        __('Did you go to :name?', ['name' => $partnership->restaurant_name]),
                        '/app',
                        'reminder-'.$partnership->id,
                    );
                    $queued++;
                }
            }
        });

        $this->info("Queued {$queued} reminder push(es).");

        return self::SUCCESS;
    }
}
