<?php

declare(strict_types=1);

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Services\ArtworkSearchService;
use App\Services\GroupDiscoveryService;
use Illuminate\Http\Request;
use Illuminate\View\View;
use cPad\Plugins\News\Models\NewsArticle;

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

    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);

        $groups = $q !== ''
            ? $this->groups->searchCards($q, $request->user(), 6)
            : $this->groups->surfaceCards($request->user(), 'featured', 4);

        $news = $q !== ''
            ? NewsArticle::query()
                ->with(['author:id,username,name', 'category:id,name,slug'])
                ->published()
                ->where(function ($builder) use ($q): void {
                    $builder->where('title', 'like', '%' . $q . '%')
                        ->orWhere('excerpt', 'like', '%' . $q . '%')
                        ->orWhere('content', 'like', '%' . $q . '%')
                        ->orWhere('meta_title', 'like', '%' . $q . '%');
                })
                ->editorialOrder()
                ->limit(4)
                ->get()
            : collect();

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