<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Controllers\Controller;
use App\Models\Artwork;
use App\Models\ContentType;
use App\Support\AvatarUrl;
use App\Services\ThumbnailPresenter;
use Illuminate\Http\Request;
use Illuminate\View\View;

class DashboardGalleryController extends Controller
{
    public function index(Request $request): View
    {
        $user = $request->user();
        $perPage = 24;

        $query = Artwork::query()
            ->with([
                'user:id,name,username',
                'user.profile:user_id,avatar_hash',
                'categories:id,name,slug,content_type_id,parent_id,sort_order',
                'categories.contentType:id,name,slug',
            ])
            ->where('user_id', (int) $user->id)
            ->orderBy('published_at', 'desc');

        $artworks = $query->paginate($perPage)->withQueryString();
        $artworks->setCollection(
            $artworks->getCollection()->map(fn (Artwork $artwork) => $this->presentArtwork($artwork))
        );

        $mainCategories = ContentType::ordered()
            ->get(['name', 'slug'])
            ->map(function (ContentType $type) {
                return (object) [
                    'id' => $type->id,
                    'name' => $type->name,
                    'slug' => $type->slug,
                    'url' => '/' . strtolower($type->slug),
                ];
            });

        return view('gallery.index', [
            'gallery_type' => 'dashboard',
            'mainCategories' => $mainCategories,
            'subcategories' => $mainCategories,
            'contentType' => null,
            'category' => null,
            'artworks' => $artworks,
            'hero_title' => 'My Gallery',
            'hero_description' => 'Your uploaded artworks.',
            'breadcrumbs' => collect(),
            'page_title' => 'My Gallery - SkinBase',
            'page_meta_description' => 'My uploaded artworks on SkinBase',
            'page_meta_keywords' => 'my gallery, uploads, skinbase',
            'page_canonical' => url('/dashboard/gallery'),
        ]);
    }

    private function presentArtwork(Artwork $artwork): object
    {
        $primary = $artwork->categories->sortBy('sort_order')->first();
        $present = ThumbnailPresenter::present($artwork, 'md');
        $group = $artwork->group;
        $isGroupPublisher = $group !== null;
        $displayName = $isGroupPublisher ? ($group->name ?? 'Skinbase') : ($artwork->user?->name ?? 'Skinbase');
        $username = $isGroupPublisher ? '' : ($artwork->user?->username ?? '');
        $avatarUrl = $isGroupPublisher
            ? $group->avatarUrl()
            : AvatarUrl::forUser(
                (int) ($artwork->user_id ?? 0),
                $artwork->user?->profile?->avatar_hash ?? null,
                64
            );
        $profileUrl = $isGroupPublisher ? $group->publicUrl() : ($username !== '' ? '/@' . $username : null);

        return (object) [
            'id' => $artwork->id,
            'name' => $artwork->title,
            'content_type_name' => $primary?->contentType?->name ?? '',
            'content_type_slug' => $primary?->contentType?->slug ?? '',
            'category_name' => $primary?->name ?? '',
            'category_slug' => $primary?->slug ?? '',
            'thumb_url' => $present['url'],
            'thumb_srcset' => $present['srcset'] ?? $present['url'],
            'uname' => $displayName,
            'username' => $username,
            'avatar_url' => $avatarUrl,
            'profile_url' => $profileUrl,
            'published_as_type' => $isGroupPublisher ? 'group' : 'user',
            'publisher' => [
                'type' => $isGroupPublisher ? 'group' : 'user',
                'name' => $displayName,
                'username' => $username,
                'avatar_url' => $avatarUrl,
                'profile_url' => $profileUrl,
            ],
            'published_at' => $artwork->published_at,
            'slug' => $artwork->slug ?? '',
            'width' => $artwork->width ?? null,
            'height' => $artwork->height ?? null,
        ];
    }
}
