<?php

namespace App\Services;

use App\Models\Task;
use App\Models\User;
use App\Models\AppNotification;
use Carbon\Carbon;

class AlertService
{
    public function checkOverdueTasks()
    {
        $overdue = Task::where('deadline', '<', now())
            ->whereHas('status', fn($q) => $q->whereNotIn('slug', ['completed', 'cancelled']))
            ->with('assignees')
            ->get();

        foreach ($overdue as $task) {
            foreach ($task->assignees as $user) {
                AppNotification::create([
                    'user_id' => $user->id,
                    'title' => '🚨 Task Overdue: ' . $task->title,
                    'message' => 'This task has passed its deadline. Please update the status or request an extension.',
                    'type' => 'danger',
                ]);
            }
        }
        return $overdue->count();
    }

    public function checkOverloadedEmployees()
    {
        $employees = User::whereHas('roles', fn($q) => $q->where('slug', 'developer'))->get();
        $count = 0;

        foreach ($employees as $user) {
            $stats = $user->workloadStats();
            if ($stats['is_overloaded']) {
                AppNotification::create([
                    'user_id' => $user->id,
                    'title' => '⚠️ Workload Warning',
                    'message' => 'You are currently assigned over 40 hours of work. Consider delegating tasks.',
                    'type' => 'warning',
                ]);
                $count++;
            }
        }
        return $count;
    }
}
