<?php

namespace App\Jobs;

use App\Models\Task;
use App\Notifications\TaskOverdueNotification;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class NotifyOverdueTasks implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function handle(): void
    {
        $overdueTasks = Task::overdue()
            ->with(['assignee', 'project'])
            ->get();

        foreach ($overdueTasks as $task) {
            // Notify assignee
            if ($task->assignee) {
                $task->assignee->notify(new TaskOverdueNotification($task));
            }

            // Notify creator (if different from assignee)
            if ($task->creator && $task->creator->id !== $task->assignee?->id) {
                $task->creator->notify(new TaskOverdueNotification($task));
            }
        }
    }
}
