<?php

namespace App\Console\Commands;

use App\Models\IssueTask;
use App\Notifications\IssueTaskOverdueNotification;
use Illuminate\Console\Command;

class NotifyOverdueIssueTasks extends Command
{
    protected $signature = 'issues:notify-overdue';

    protected $description = 'Notify assignees of issue tasks that are overdue (one notification per task)';

    public function handle(): int
    {
        $tasks = IssueTask::overdue()
            ->whereNull('overdue_notified_at')
            ->whereNotNull('assigned_to')
            ->with(['assignee', 'issue'])
            ->get();

        $sent = 0;
        foreach ($tasks as $task) {
            if ($task->assignee) {
                $task->assignee->notify(new IssueTaskOverdueNotification($task));
                $sent++;
            }
            $task->forceFill(['overdue_notified_at' => now()])->save();
        }

        $this->info("Tareas vencidas notificadas: {$sent}");

        return self::SUCCESS;
    }
}
