<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StorePostRequest;
use App\Http\Requests\UpdatePostRequest;
use App\Http\Resources\PostResource;
use App\Models\Post;
use App\Services\PostService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Facades\Gate;

class PostController extends Controller
{
    public function __construct(private PostService $postService) {}

    public function index(Request $request): AnonymousResourceCollection
    {
        $posts = $this->postService->paginate($request->user());
        return PostResource::collection($posts);
    }

    public function store(StorePostRequest $request): JsonResponse
    {
        $post = $this->postService->create(
            $request->user(),
            $request->validated(),
            $request->file('image')
        );

        $post->load(['user', 'likes.user']);
        $post->loadCount(['comments', 'likes']);

        return response()->json([
            'message' => 'Post created.',
            'post'    => new PostResource($post),
        ], 201);
    }

    public function show(Request $request, Post $post): JsonResponse
    {
        Gate::authorize('view', $post);

        $post->load(['user', 'likes.user']);
        $post->loadCount(['comments', 'likes']);

        return response()->json(['post' => new PostResource($post)]);
    }

    public function update(UpdatePostRequest $request, Post $post): JsonResponse
    {
        Gate::authorize('update', $post);

        $updated = $this->postService->update($post, $request->validated());
        $updated->load('user');
        $updated->loadCount(['comments', 'likes']);

        return response()->json([
            'message' => 'Post updated.',
            'post'    => new PostResource($updated),
        ]);
    }

    public function destroy(Request $request, Post $post): JsonResponse
    {
        Gate::authorize('delete', $post);

        $this->postService->delete($post);

        return response()->json(['message' => 'Post deleted.']);
    }
}
