<?php

namespace App\Http\Controllers;

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

class ToDoListController extends Controller
{
    public function index()
    {
        $this->authorize('viewAny', ToDoList::class);

        return ToDoListResource::collection(request()->user()->toDoLists);
    }

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

        $toDoList = request()->user()->toDoLists()->create($this->validateData());

        return (new ToDoListResource($toDoList))
            ->response()
            ->setStatusCode(201);
    }

    public function show(ToDoList $toDoList)
    {
        $this->authorize('view', $toDoList);

        return new ToDoListResource($toDoList);
    }

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

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

        return (new ToDoListResource($toDoList))
            ->response()
            ->setStatusCode(200);
    }

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

        $toDoList->delete();

        return response([], 204);
    }

    private function validateData()
    {
        return request()->validate([
            'name' => 'required',
        ]);
    }
}
