<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Relations\MorphMany;

/**
 * Safe wrapper for TaskSystem's HasTasks trait.
 *
 * Provides task relationship methods that gracefully handle TaskSystem being disabled.
 * Use this trait instead of Modules\TaskSystem\App\Traits\HasTasks to ensure
 * your module works independently even when TaskSystem is not installed.
 */
trait SafeHasTasks
{
    /**
     * Get all tasks for this model.
     */
    public function tasks(): MorphMany
    {
        if (! moduleExists('TaskSystem')) {
            // Return empty relationship that never matches
            return $this->morphMany(static::class, 'taskable')->whereRaw('1=0');
        }

        $taskClass = 'Modules\\TaskSystem\\App\\Models\\Task';

        return $this->morphMany($taskClass, 'taskable');
    }

    /**
     * Get pending (not completed) tasks for this model.
     */
    public function pendingTasks(): MorphMany
    {
        return $this->tasks()->whereNull('completed_at');
    }

    /**
     * Get completed tasks for this model.
     */
    public function completedTasks(): MorphMany
    {
        return $this->tasks()->whereNotNull('completed_at');
    }

    /**
     * Get overdue tasks for this model.
     */
    public function overdueTasks(): MorphMany
    {
        return $this->tasks()
            ->whereNull('completed_at')
            ->where('due_date', '<', now());
    }

    /**
     * Get the count of pending tasks.
     */
    public function getPendingTasksCountAttribute(): int
    {
        if (! moduleExists('TaskSystem')) {
            return 0;
        }

        return $this->pendingTasks()->count();
    }

    /**
     * Get the count of completed tasks.
     */
    public function getCompletedTasksCountAttribute(): int
    {
        if (! moduleExists('TaskSystem')) {
            return 0;
        }

        return $this->completedTasks()->count();
    }

    /**
     * Check if this model has any pending tasks.
     */
    public function hasPendingTasks(): bool
    {
        if (! moduleExists('TaskSystem')) {
            return false;
        }

        return $this->pendingTasks()->exists();
    }

    /**
     * Check if this model has any overdue tasks.
     */
    public function hasOverdueTasks(): bool
    {
        if (! moduleExists('TaskSystem')) {
            return false;
        }

        return $this->overdueTasks()->exists();
    }
}
