<?php

namespace App\Console\Commands;

use App\Models\Task;
use App\Notifications\TaskDueSoonNotification;
use Illuminate\Console\Command;

class SendDueSoonNotifications extends Command
{
    protected $signature = 'tasks:notify-due-soon';
    protected $description = 'Send notifications for tasks due within 24 hours';

    public function handle(): int
    {
        $tasks = Task::where('is_completed', false)
            ->whereNotNull('due_date')
            ->whereNotNull('assignee_id')
            ->whereBetween('due_date', [now(), now()->addHours(24)])
            ->with('assignee')
            ->get();

        $sent = 0;

        foreach ($tasks as $task) {
            // Avoid duplicate notifications: check if already notified today
            $alreadyNotified = $task->assignee->notifications()
                ->where('type', TaskDueSoonNotification::class)
                ->where('created_at', '>=', now()->startOfDay())
                ->whereJsonContains('data->task_id', $task->id)
                ->exists();

            if (!$alreadyNotified) {
                $task->assignee->notify(new TaskDueSoonNotification($task));
                $sent++;
            }
        }

        $this->info("Sent {$sent} due-soon notifications.");

        return Command::SUCCESS;
    }
}
