<?php

namespace App\Http\Controllers\Api\Posts;

use App\Http\Controllers\Controller;
use App\Models\Post;
use App\Models\PostSave;
use App\Services\Posts\PostCountersService;
use App\Services\Posts\PostFeedService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * POST   /api/posts/{id}/save
 * DELETE /api/posts/{id}/save
 * GET    /api/posts/saved
 */
class PostSaveController extends Controller
{
    public function __construct(
        private PostCountersService $counters,
        private PostFeedService     $feedService,
    ) {}

    public function save(Request $request, int $id): JsonResponse
    {
        $post = Post::where('status', Post::STATUS_PUBLISHED)->findOrFail($id);
        $user = $request->user();

        if (PostSave::where('post_id', $post->id)->where('user_id', $user->id)->exists()) {
            return response()->json(['message' => 'Already saved.', 'saved' => true], 200);
        }

        PostSave::create(['post_id' => $post->id, 'user_id' => $user->id]);
        $this->counters->incrementSaves($post);

        return response()->json(['message' => 'Post saved.', 'saved' => true, 'saves_count' => $post->fresh()->saves_count]);
    }

    public function unsave(Request $request, int $id): JsonResponse
    {
        $post   = Post::findOrFail($id);
        $user   = $request->user();
        $save   = PostSave::where('post_id', $post->id)->where('user_id', $user->id)->first();

        if (! $save) {
            return response()->json(['message' => 'Not saved.', 'saved' => false], 200);
        }

        $save->delete();
        $this->counters->decrementSaves($post);

        return response()->json(['message' => 'Post unsaved.', 'saved' => false, 'saves_count' => $post->fresh()->saves_count]);
    }

    public function index(Request $request): JsonResponse
    {
        $user   = $request->user();
        $page   = max(1, (int) $request->query('page', 1));
        $result = $this->feedService->getSavedFeed($user, $page);

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

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