<?php

namespace App\Http\Controllers\User;

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

class UserController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();
        if (! $user) {
            return redirect()->route('login');
        }

        try {
            $profile = app(\App\Services\LegacyService::class)->userAccount($user->id);
        } catch (\Throwable $e) {
            $profile = null;
        }

        // Hero background: prefer featured wallpapers or photography
        $heroBgUrl = Artwork::public()
            ->published()
            ->whereNotNull('hash')
            ->whereNotNull('thumb_ext')
            ->whereHas('features', function ($q) {
                $q->where('is_active', true)
                  ->where(function ($q2) {
                      $q2->whereNull('expires_at')->orWhere('expires_at', '>', now());
                  });
            })
            ->whereHas('categories', function ($q) {
                // content_type_id 2 = Wallpapers, 3 = Photography
                $q->whereIn('content_type_id', [2, 3]);
            })
            ->inRandomOrder()
            ->limit(1)
            ->first()?->thumbUrl('lg');

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