<?php

declare(strict_types=1);

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Services\ArtworkSearchService;
use Illuminate\Http\Request;
use Illuminate\View\View;

final class SearchController extends Controller
{
    public function __construct(private readonly ArtworkSearchService $search) {}

    public function index(Request $request): View
    {
        $q    = trim((string) $request->query('q', ''));
        $sort = $request->query('sort', 'latest');

        $sortMap = [
            'popular'   => 'views:desc',
            'likes'     => 'likes:desc',
            'latest'    => 'created_at:desc',
            'downloads' => 'downloads:desc',
        ];

        $artworks = $q !== ''
            ? $this->search->search($q, [
                'sort' => ($sortMap[$sort] ?? 'created_at:desc'),
            ])
            : $this->search->popular(24);

        return view('search.index', [
            'q'                     => $q,
            'sort'                  => $sort,
            'artworks'              => $artworks,
            'page_title'            => $q !== '' ? 'Search: ' . $q . ' — Skinbase' : 'Search — Skinbase',
            'page_meta_description' => 'Search Skinbase for artworks, photography, wallpapers and skins.',
            'page_robots'           => 'noindex,follow',
        ]);
    }
}
