<?php

namespace App\Http\Controllers\Admin;

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

class EmotionTagController extends Controller
{
    public function index(): View
    {
        EmotionTag::seedDefaults();

        return view('admin.emotion-tags.index', [
            'tags' => EmotionTag::orderBy('sort_order')->orderBy('name')->get(),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        EmotionTag::create($this->validated($request));

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

    public function update(Request $request, EmotionTag $emotionTag): RedirectResponse
    {
        $emotionTag->update($this->validated($request));

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

    public function destroy(EmotionTag $emotionTag): RedirectResponse
    {
        $emotionTag->delete();

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

    private function validated(Request $request): array
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'description' => ['nullable', 'string', 'max:1000'],
            'sort_order' => ['required', 'integer', 'min:0', 'max:9999'],
            'is_active' => ['nullable', 'boolean'],
        ]);
        $data['is_active'] = $request->boolean('is_active');

        return $data;
    }
}
