<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\MistakeTag;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class MistakeTagController extends Controller
{
    public function index(): View
    {
        MistakeTag::ensureDefaults();

        return view('admin.mistake-tags.index', [
            'tags' => MistakeTag::whereNull('user_id')->orderBy('name')->get(),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        MistakeTag::create($this->validated($request) + ['user_id' => null]);

        return back()->with('success', 'Mistake tag created.');
    }

    public function update(Request $request, MistakeTag $mistakeTag): RedirectResponse
    {
        abort_unless($mistakeTag->user_id === null, 403);
        $mistakeTag->update($this->validated($request));

        return back()->with('success', 'Mistake tag updated.');
    }

    public function destroy(MistakeTag $mistakeTag): RedirectResponse
    {
        abort_unless($mistakeTag->user_id === null, 403);
        $mistakeTag->delete();

        return back()->with('success', 'Mistake tag deleted.');
    }

    private function validated(Request $request): array
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'is_default' => ['nullable', 'boolean'],
            'is_active' => ['nullable', 'boolean'],
        ]);
        $data['is_default'] = $request->boolean('is_default');
        $data['is_active'] = $request->boolean('is_active');

        return $data;
    }
}
