<?php

namespace App\Http\Controllers;

use App\Http\Resources\ToDo as ToDoResource;
use App\Http\Resources\ToDoList as ToDoListResource;
use App\Models\ToDo;
use App\Models\ToDoList;
use Illuminate\Http\Request;

class ToDoController extends Controller
{
    public function store(ToDoList $toDoList)
    {
        $this->authorize('create', ToDoList::class);

        $lastToDo = $toDoList->toDos()->orderBy('order', 'desc')->first();

        request()['order'] = ($lastToDo) ? $lastToDo->order + 1 : 1;

        $toDo = $toDoList->toDos()->create($this->validateData());

        return (new ToDoResource($toDo))
            ->response()
            ->setStatusCode(201);
    }

    public function update(ToDoList $toDoList, ToDo $toDo)
    {
        $this->authorize('update', $toDoList);

        $toDo->update($this->validateData());

        return (new ToDoResource($toDo))
            ->response()
            ->setStatusCode(200);
    }

    public function destroy(ToDoList $toDoList, ToDo $toDo)
    {
        $this->authorize('delete', $toDoList);

        $toDo->delete();

        return response([], 204);
    }

    public function changeOrder(ToDoList $toDoList, ToDo $toDo)
    {
        $this->authorize('update', $toDoList);

        $toDoChanged = $toDoList->toDos()->where('order', (int) request()['new-order'])->first();

        $toDoChanged->update(['order' => (int) $toDo->order]);
        $toDo->update(['order' => (int) request()['new-order']]);

        return (new ToDoResource($toDo))
            ->response()
            ->setStatusCode(200);
    }

    public function checkedToogle(ToDoList $toDoList, ToDo $toDo)
    {
        $this->authorize('update', $toDoList);

        ($toDo->checked_at) ? $toDo->checked_at = NULL :  $toDo->checked_at = now();
        $toDo->save();

        return (new ToDoResource($toDo))
            ->response()
            ->setStatusCode(200);
    }

    private function validateData()
    {
        return request()->validate([
            'name' => 'required',
            'order' => 'integer|min:1|max:1000000',
        ]);
    }
}
