<?php

namespace App\Http\Controllers;

use App\Http\Requests\FindAnagramWordsRequest;
use App\Services\AnagramSearch;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Validator;
use Illuminate\View\View;

class AnagramController extends Controller
{
    public function __construct(private readonly AnagramSearch $search) {}

    public function index(): View
    {
        return view('index');
    }

    public function find(FindAnagramWordsRequest $request): RedirectResponse
    {
        return redirect()->route('results', $request->validated('anagram'));
    }

    public function results(string $anagram): View|RedirectResponse
    {
        // The URL segment bypasses the form request, so it gets the same rules.
        $anagram = strtolower($anagram);

        $validator = Validator::make(
            ['anagram' => $anagram],
            (new FindAnagramWordsRequest)->rules(),
            (new FindAnagramWordsRequest)->messages(),
        );

        if ($validator->fails()) {
            return redirect()
                ->route('home')
                ->withErrors($validator)
                ->withInput(['anagram' => $anagram]);
        }

        return view('index', [
            'anagram' => $anagram,
            'matches' => $this->search->find($anagram),
        ]);
    }
}
