<?php

namespace App\Http\Controllers\Community;

use App\Http\Controllers\Controller;
use App\Models\Artwork;
use App\Services\ArtworkService;
use Illuminate\Http\Request;

class LatestController extends Controller
{
    protected ArtworkService $artworks;

    public function __construct(ArtworkService $artworks)
    {
        $this->artworks = $artworks;
    }

    public function index(Request $request)
    {
        $perPage = 21;

        $artworks = $this->artworks->browsePublicArtworks($perPage);
        $artworks->getCollection()->load([
            'user:id,name,username',
            'user.profile:user_id,avatar_hash',
        ]);

        $artworks->getCollection()->transform(function (Artwork $artwork) {
            $primaryCategory = $artwork->categories->sortBy('sort_order')->first();
            $categoryName = $primaryCategory->name ?? '';
            $gid = $primaryCategory ? ((int) $primaryCategory->id % 5) * 5 : 0;
            $present = \App\Services\ThumbnailPresenter::present($artwork, 'md');

            return (object) [
                'id' => $artwork->id,
                'name' => $artwork->title,
                'content_type_name' => $primaryCategory?->contentType?->name ?? '',
                'content_type_slug' => $primaryCategory?->contentType?->slug ?? '',
                'category_name' => $categoryName,
                'category_slug' => $primaryCategory?->slug ?? '',
                'gid_num' => $gid,
                'slug' => $artwork->slug,
                'thumb_url' => $present['url'],
                'thumb_srcset' => $present['srcset'] ?? $present['url'],
                'uname' => $artwork->user->name ?? 'Skinbase',
                'username' => $artwork->user->username ?? '',
                'user_id' => $artwork->user->id,
                'avatar_hash' => $artwork->user->profile->avatar_hash ?? null,
                'avatar_url' => \App\Support\AvatarUrl::forUser((int) $artwork->user->id, $artwork->user->profile->avatar_hash ?? null, 64),
                'width' => $artwork->width,
                'height' => $artwork->height,
                'published_at' => $artwork->published_at, // required by CursorPaginator
            ];
        });

        return view('web.uploads.latest', [
            'artworks' => $artworks,
            'page_title' => 'Latest Artworks',
        ]);
    }
}
