<?php

namespace App\Http\Controllers\Legacy;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\ArtworkComment;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;

class LatestCommentsController extends Controller
{
    public function index(Request $request)
    {
        $hits = 20;

        // Join artwork_comments -> artwork -> user, but only include artworks that are public, approved and published
        $query = ArtworkComment::with(['user', 'artwork'])
            ->whereHas('artwork', function ($q) {
                $q->public()->published()->whereNull('deleted_at');
            })
            ->orderByDesc('created_at');

        $comments = $query->paginate($hits)->withQueryString();

        // Shape results for legacy view
        $comments->getCollection()->transform(function (ArtworkComment $c) {
            $art = $c->artwork;
            $user = $c->user;

            $present = $art ? \App\Services\ThumbnailPresenter::present($art, 'md') : null;
            $thumb = $present ? ($present['url']) : 'https://files.skinbase.org/default/missing_md.webp';

            return (object) [
                'comment_id' => $c->getKey(),
                'comment_description' => $c->content,
                'commenter_id' => $c->user_id,
                'country' => $user->country ?? null,
                'icon' => $user ? DB::table('user_profiles')->where('user_id', $user->id)->value('avatar_hash') : null,
                'uname' => $user->username ?? $user->name ?? 'User',
                'signature' => $user->signature ?? null,
                'user_type' => $user->role ?? null,
                'id' => $art->id ?? null,
                'name' => $art->title ?? null,
                'picture' => $art->file_name ?? null,
                'thumb' => $thumb,
                'artwork_slug' => $art->slug ?? Str::slug($art->title ?? ''),
                'datetime' => $c->created_at?->toDateTimeString() ?? now()->toDateTimeString(),
            ];
        });

        $page_title = 'Latest Comments';

        return view('legacy::latest-comments', compact('page_title', 'comments'));
    }
}
