<?php

namespace App\Http\Controllers;

use App\Http\Requests\PostReviewsRequest;
use App\Http\Resources\PostReviewsResource;
use App\Models\MealPosts;
use App\Models\PostReviews;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Http\Response;

class PostReviewsController extends Controller
{
    public function index(Request $request, MealPosts $mealPost): AnonymousResourceCollection
    {
        $perPage = max(1, min($request->integer('per_page', 15), 100));

        $reviews = $mealPost->reviews()
            ->with('user:id,name,avatar_url')
            ->latest()
            ->paginate($perPage)
            ->withQueryString();

        return PostReviewsResource::collection($reviews);
    }

    public function store(PostReviewsRequest $request, MealPosts $mealPost): JsonResponse
    {
        $userId = $request->user()->getKey();

        abort_if(
            PostReviews::query()
                ->where('meal_post_id', $mealPost->getKey())
                ->where('user_id', $userId)
                ->exists(),
            409,
            __('api.post_reviews.already_exists')
        );

        $postReview = PostReviews::create([
            ...$request->validated(),
            'meal_post_id' => $mealPost->getKey(),
            'user_id' => $userId,
        ]);

        return (new PostReviewsResource($postReview->load('user:id,name,avatar_url')))
            ->response()
            ->setStatusCode(201);
    }

    public function show(PostReviews $postReview): PostReviewsResource
    {
        return new PostReviewsResource($postReview->loadMissing(
            'mealPost.ingredients',
            'mealPost.user:id,name,avatar_url',
            'user:id,name,avatar_url',
        ));
    }

    public function update(PostReviewsRequest $request, PostReviews $postReview): PostReviewsResource
    {
        $this->abortIfNotOwner($request, $postReview);

        $postReview->update($request->validated());

        return new PostReviewsResource($postReview->refresh()->loadMissing('user:id,name,avatar_url'));
    }

    public function destroy(Request $request, PostReviews $postReview): Response
    {
        $this->abortIfNotOwner($request, $postReview);

        $postReview->delete();

        return response()->noContent();
    }

    private function abortIfNotOwner(Request $request, PostReviews $postReview): void
    {
        abort_unless($request->user(), 401);
        abort_unless($postReview->user_id === $request->user()->getKey(), 404);
    }
}
