<?php

namespace App\Http\Controllers\Api\Posts;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\Posts\PostFeedService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class PostFeedController extends Controller
{
    public function __construct(private PostFeedService $feedService) {}

    // ─────────────────────────────────────────────────────────────────────────
    // Profile feed — GET /api/posts/profile/{username}
    // ─────────────────────────────────────────────────────────────────────────

    public function profile(Request $request, string $username): JsonResponse
    {
        $profileUser = User::where('username', $username)->firstOrFail();
        $viewerId    = $request->user()?->id;
        $page        = max(1, (int) $request->query('page', 1));

        $paginated = $this->feedService->getProfileFeed($profileUser, $viewerId, $page);

        $formatted = collect($paginated['data'])
            ->map(fn ($post) => $this->feedService->formatPost($post, $viewerId))
            ->values();

        return response()->json([
            'data' => $formatted,
            'meta' => $paginated['meta'],
        ]);
    }

    // ─────────────────────────────────────────────────────────────────────────
    // Following feed — GET /api/posts/following
    // ─────────────────────────────────────────────────────────────────────────

    public function following(Request $request): JsonResponse
    {
        $user   = $request->user();
        $page   = max(1, (int) $request->query('page', 1));
        $filter = $request->query('filter', 'all');

        $result = $this->feedService->getFollowingFeed($user, $page, $filter);

        $viewerId  = $user->id;
        $formatted = array_map(
            fn ($post) => $this->feedService->formatPost($post, $viewerId),
            $result['data'],
        );

        return response()->json([
            'data' => $formatted,
            'meta' => $result['meta'],
        ]);
    }
}
