<?php

namespace App\Services;

use App\Models\Task;
use Illuminate\Database\Eloquent\Model;

class TaskService
{
    public function addTask(
        HistoryService $history,
        Model $owner,
        $title,
        $due_at,
        $description = null,
        $target_user_id = null
    ) {
        $task = Task::create([
            'owner_type' => $owner->getMorphClass(),
            'owner_id' => $owner->getKey(),
            'user_id' => $target_user_id ?: auth()->id(),
            'title' => $title,
            'description' => $description,
            'due_at' => $due_at,
        ]);

        $label = $this->buildLabel($task);

        $history->add($owner, "Added task {$label}");

        return $task;
    }

    public function completeTask(HistoryService $history, Task $task, Model $owner): void
    {
        $task->completed_at = now();
        $task->save();

        $history->add($owner, "Completed task: {$task->title}");
    }

    private function buildLabel(Task $task): string
    {
        $title = $task->title ? "titled '{$task->title}'" : null;
        $description = $task->description ? "described as '{$task->description}'" : null;
        $due = $task->due_at ? "due on " . $task->due_at->format('Y-m-d') : null;

        return implode(' and ', array_filter([$title, $description, $due]));
    }
}