<?php

namespace App\Models;

use App\Services\EventTasksCacheService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Task extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $table = 'tasks';

    protected $guarded = [];

    protected $casts = [
        'due_date' => 'datetime',
        'is_completed' => 'bool',
        'title' => 'array',
        'description' => 'array',
        'example_text' => 'array',
    ];

    public function emotion(): BelongsTo
    {
        return $this->belongsTo(Emotion::class);
    }

    public function eventType(): BelongsTo
    {
        return $this->belongsTo(EventType::class, 'event_type_id');
    }

    public function taskCollection(): BelongsTo
    {
        return $this->belongsTo(TaskCollection::class, 'collection_id');
    }

    public function tenant(): BelongsTo
    {
        return $this->belongsTo(Tenant::class);
    }

    public function sourceTask(): BelongsTo
    {
        return $this->belongsTo(Task::class, 'source_task_id');
    }

    public function derivedTasks(): HasMany
    {
        return $this->hasMany(Task::class, 'source_task_id');
    }

    public function sourceCollection(): BelongsTo
    {
        return $this->belongsTo(TaskCollection::class, 'source_collection_id');
    }

    public function scopeForTenant(Builder $query, ?int $tenantId): Builder
    {
        return $query->where(function (Builder $innerQuery) use ($tenantId) {
            $innerQuery->whereNull('tenant_id');

            if ($tenantId) {
                $innerQuery->orWhere('tenant_id', $tenantId);
            }
        });
    }

    protected static function booted(): void
    {
        static::creating(function (Task $task) {
            if (! $task->slug) {
                $task->slug = static::generateSlug(
                    $task->title['en'] ?? $task->title['de'] ?? 'task'
                );
            }
        });

        static::saved(function (Task $task) {
            app(EventTasksCacheService::class)->forgetForTask($task);
        });

        static::deleted(function (Task $task) {
            app(EventTasksCacheService::class)->forgetForTask($task);
        });
    }

    protected static function generateSlug(string $base): string
    {
        $slugBase = Str::slug($base) ?: 'task';

        do {
            $slug = $slugBase.'-'.Str::random(6);
        } while (static::where('slug', $slug)->exists());

        return $slug;
    }

    public function assignedEvents(): BelongsToMany
    {
        return $this->belongsToMany(Event::class, 'event_task', 'task_id', 'event_id')
            ->withPivot(['sort_order'])
            ->withTimestamps();
    }
}
