<?php

namespace App\Http\Controllers;

use App\Http\Resources\Memo as MemoResource;
use App\Models\Memo;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

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

        return MemoResource::collection(request()->user()->memos);
    }

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

        $memo = request()->user()->memos()->create($this->validateData());

        return (new MemoResource($memo))
            ->response()
            ->setStatusCode(Response::HTTP_CREATED);
    }

    public function show(Memo $memo)
    {
        $this->authorize('view', $memo);

        return new MemoResource($memo);
    }

    public function update(Memo $memo)
    {
        $this->authorize('update', $memo);

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

        return (new MemoResource($memo))
            ->response()
            ->setStatusCode(Response::HTTP_OK);
    }

    public function destroy(Memo $memo)
    {
        $this->authorize('delete', $memo);

        $memo->delete();

        return response([], Response::HTTP_NO_CONTENT);
    }

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