<?php

namespace App\Http\Controllers\Community;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\ArtworkComment;
use App\Support\AvatarUrl;
use App\Services\ThumbnailPresenter;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Carbon\Carbon;

class LatestCommentsController extends Controller
{
    private const PER_PAGE = 20;

    public function index(Request $request)
    {
        $page_title = 'Latest Comments';

        // Build initial (first-page, type=all) data for React SSR props
        $initialData = Cache::remember('comments.latest.all.page1', 120, function () {
            return ArtworkComment::with(['user', 'user.profile', 'artwork'])
                ->whereHas('artwork', function ($q) {
                    $q->public()->published()->whereNull('deleted_at');
                })
                ->orderByDesc('artwork_comments.created_at')
                ->paginate(self::PER_PAGE);
        });

        $items = $initialData->getCollection()->map(function (ArtworkComment $c) {
            $art  = $c->artwork;
            $user = $c->user;

            $present    = $art ? ThumbnailPresenter::present($art, 'md') : null;
            $thumb      = $present ? ($present['url'] ?? null) : null;
            $userId     = (int) ($c->user_id ?? 0);
            $avatarHash = $user?->profile?->avatar_hash ?? null;

            return [
                'comment_id'   => $c->getKey(),
                'comment_text' => e(strip_tags($c->content ?? '')),
                'created_at'   => $c->created_at?->toIso8601String(),
                'time_ago'     => $c->created_at ? Carbon::parse($c->created_at)->diffForHumans() : null,

                'commenter' => [
                    'id'          => $userId,
                    'username'    => $user?->username ?? null,
                    'display'     => $user?->username ?? $user?->name ?? 'User',
                    'profile_url' => $user?->username ? '/@' . $user->username : '/profile/' . $userId,
                    'avatar_url'  => AvatarUrl::forUser($userId, $avatarHash, 64),
                ],

                'artwork' => $art ? [
                    'id'    => $art->id,
                    'title' => $art->title,
                    'slug'  => $art->slug ?? Str::slug($art->title ?? ''),
                    'url'   => '/art/' . $art->id . '/' . ($art->slug ?? Str::slug($art->title ?? '')),
                    'thumb' => $thumb,
                ] : null,
            ];
        });

        $props = [
            'initialComments' => $items->values()->all(),
            'initialMeta'     => [
                'current_page' => $initialData->currentPage(),
                'last_page'    => $initialData->lastPage(),
                'per_page'     => $initialData->perPage(),
                'total'        => $initialData->total(),
                'has_more'     => $initialData->hasMorePages(),
            ],
            'isAuthenticated' => (bool) auth()->user(),
        ];

        return view('web.comments.latest', compact('page_title', 'props'));
    }
}
