<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Controllers\Controller;
use App\Services\ReceivedCommentsInboxService;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;

class CommentController extends Controller
{
    public function __construct(private readonly ReceivedCommentsInboxService $inbox) {}

    public function received(Request $request): View
    {
        $user = $request->user();
        $search = trim((string) $request->query('q', ''));
        $sort = strtolower((string) $request->query('sort', 'newest'));

        if (! in_array($sort, ['newest', 'oldest'], true)) {
            $sort = 'newest';
        }

        $baseQuery = $this->inbox->queryForUser($user)
            ->with(['user.profile', 'artwork']);

        if ($search !== '') {
            $baseQuery->where(function ($query) use ($search): void {
                $query->where('content', 'like', '%' . $search . '%')
                    ->orWhere('raw_content', 'like', '%' . $search . '%')
                    ->orWhereHas('artwork', function ($artworkQuery) use ($search): void {
                        $artworkQuery->where('title', 'like', '%' . $search . '%')
                            ->orWhere('slug', 'like', '%' . $search . '%');
                    })
                    ->orWhereHas('user', function ($userQuery) use ($search): void {
                        $userQuery->where('username', 'like', '%' . $search . '%')
                            ->orWhere('name', 'like', '%' . $search . '%');
                    });
            });
        }

        $orderedQuery = (clone $baseQuery)
            ->orderBy('created_at', $sort === 'oldest' ? 'asc' : 'desc');

        $comments = $orderedQuery->paginate(12)->withQueryString();

        $statsBaseQuery = clone $baseQuery;
        $freshlyClearedCount = $this->inbox->unreadCountForUser($user);
        $totalComments = (clone $statsBaseQuery)->count();
        $recentComments = (clone $statsBaseQuery)->where('created_at', '>=', now()->subDays(7))->count();
        $uniqueCommenters = (clone $statsBaseQuery)->distinct('user_id')->count('user_id');
        $activeArtworks = (clone $statsBaseQuery)->distinct('artwork_id')->count('artwork_id');

        $this->inbox->markInboxRead($user);

        return view('dashboard.comments', [
            'comments' => $comments,
            'search' => $search,
            'sort' => $sort,
            'freshlyClearedCount' => $freshlyClearedCount,
            'stats' => [
                'total' => $totalComments,
                'recent' => $recentComments,
                'commenters' => $uniqueCommenters,
                'artworks' => $activeArtworks,
            ],
        ]);
    }
}
