<?php

namespace App\Http\Controllers;

use App\Http\Requests\AddReplacementRequest;
use App\Http\Requests\UpdateReplacementRequest;
use App\Http\Resources\ReplacementListResource;
use Mtc\MercuryDataModels\Replacement;

class ReplacementController extends Controller
{
    public function __construct()
    {
        $this->middleware([
            'permission:manage-replacements',
        ]);
    }

    /**
     * Show list of replacements
     *
     * @return ReplacementListResource
     */
    public function show()
    {
        return new ReplacementListResource(
            Replacement::query()
                ->orderBy('type')
                ->orderBy('original')
                ->get()
        );
    }

    /**
     * Show list of replacements types
     *
     */
    public function showTypes(): array
    {
        return Replacement::$types;
    }

    /**
     * Add replacement
     *
     * @param AddReplacementRequest $request
     * @return ReplacementListResource
     */
    public function store(AddReplacementRequest $request)
    {
        $replacement = Replacement::query()->create($request->input());
        $replacement->resetCache();

        return $this->show();
    }

    /**
     * Update replacement
     *
     * @param UpdateReplacementRequest $request
     * @param Replacement $replacement
     * @return ReplacementListResource
     */
    public function update(UpdateReplacementRequest $request, Replacement $replacement)
    {
        $replacement->update($request->input());
        $replacement->resetCache();

        return $this->show();
    }

    /**
     * Remove replacement
     *
     * @param Replacement $replacement
     * @return ReplacementListResource
     */
    public function destroy(Replacement $replacement)
    {
        $replacement->delete();
        $replacement->resetCache();

        return $this->show();
    }
}
