<?php

namespace App\Console\Commands;

use App\Models\Task;
use App\Notifications\TaskReminderNotification;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;

class SendTaskReminders extends Command
{
    protected $signature = 'tasks:send-reminders';

    protected $description = 'Send database notifications for due task reminders';

    public function handle(): int
    {
        $now = now();
        $sent = 0;

        Task::query()
            ->with('user')
            ->whereNotNull('reminder_at')
            ->where('reminder_at', '<=', $now)
            ->where('status', '!=', 'done')
            ->orderBy('reminder_at')
            ->chunkById(200, function ($tasks) use (&$sent) {
                foreach ($tasks as $task) {
                    if (! $task->user) {
                        continue;
                    }

                    $cacheKey = 'task_reminder_sent_'.$task->id.'_'.optional($task->reminder_at)->timestamp;

                    if (Cache::has($cacheKey)) {
                        continue;
                    }

                    $task->user->notify(new TaskReminderNotification($task));
                    Cache::put($cacheKey, true, now()->addDays(30));
                    $sent++;
                }
            });

        $this->info('Task reminders sent: '.$sent);

        return self::SUCCESS;
    }
}
