<?php

namespace App\Http\Controllers;

use App\Enums\FollowStatus;
use App\Enums\MealPostVisibility;
use App\Http\Resources\MealPostsResource;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class PublicUserProfileController extends Controller
{
    public function show(Request $request, User $user): JsonResponse
    {
        abort_if($user->isSuspended(), 404);

        $meals = $user->mealPosts()
            ->where('visibility', MealPostVisibility::Public->value)
            ->whereNull('hidden_at')
            ->with('user:id,name,avatar_url,account_verified_at')
            ->latest('eaten_at')
            ->limit(18)
            ->get();

        return response()->json([
            'data' => [
                'user' => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'bio' => $user->bio,
                    'avatarUrl' => $user->avatar_url
                        ? asset(Storage::url($user->avatar_url))
                        : null,
                    'accountVerified' => $user->account_verified_at !== null,
                ],
                'stats' => [
                    'mealsCount' => $user->mealPosts()
                        ->where('visibility', MealPostVisibility::Public->value)
                        ->whereNull('hidden_at')
                        ->count(),
                    'followersCount' => $user->followers()
                        ->wherePivot('status', FollowStatus::Accepted)
                        ->count(),
                    'followingCount' => $user->following()
                        ->wherePivot('status', FollowStatus::Accepted)
                        ->count(),
                ],
                'isFollowing' => $request->user()
                    ? $request->user()->following()
                        ->where('following_id', $user->id)
                        ->whereIn('status', [FollowStatus::Accepted, FollowStatus::Pending])
                        ->exists()
                    : false,
                'meals' => MealPostsResource::collection($meals)->resolve($request),
            ],
        ]);
    }
}
