<?php

namespace App\Http\Controllers\Legacy;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Services\ArtworkService;
use App\Models\User;
use App\Models\Artwork;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class ProfileController extends Controller
{
    protected ArtworkService $artworkService;

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

    public function show(Request $request, ?int $id = null, ?string $slug = null)
    {
        // Support /profile (current user) and /profile/{id}/{slug}
        $id = $id ?? (Auth::check() ? Auth::id() : null);

        if (! $id) {
            abort(404);
        }

        $user = User::find($id);

        if (! $user) {
            abort(404);
        }

        // Determine visibility: owner sees all, others only public+approved+published
        $isOwner = Auth::check() && Auth::id() === $user->id;

        $perPage = 24;

        // Use ArtworkService to fetch artworks for the profile
        $artworks = $this->artworkService->getArtworksByUser($user->id, $isOwner, $perPage);

        // Shape data for legacy view expectations
        $artworks->getCollection()->transform(function (Artwork $art) {
            $present = \App\Services\ThumbnailPresenter::present($art, 'md');

            return (object) [
                'id' => $art->id,
                'name' => $art->title,
                'picture' => $art->file_name,
                'datum' => $art->published_at,
                'thumb' => $present['url'],
                'thumb_srcset' => $present['srcset'] ?? $present['url'],
                'uname' => $art->user->name ?? 'Skinbase',
            ];
        });

        // Map new User model to legacy view shape expected by templates
        $legacyUser = (object) [
            'user_id' => $user->id,
            'uname' => $user->name,
            'real_name' => $user->name,
            'icon' => DB::table('user_profiles')->where('user_id', $user->id)->value('avatar_hash'),
            'about_me' => $user->bio ?? null,
        ];

        return view('legacy::profile', [
            'user' => $legacyUser,
            'artworks' => $artworks,
        ]);
    }
}
