<?php

namespace App\Services;

use App\Models\Task;

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

        $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;

        $parts = array_filter([$title, $description, $due]);

        $label = implode(' and ', $parts);

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

        return $task;
    }

    public function completeTask(HistoryService $historyService, Task $task) {
        $task->completed_at = now();
        $task->save();

        $historyService->add(auth()->user(), "Completed task: " . $task->title);
    }
}