<?php

namespace App\Http\Controllers;

use App\Http\Requests\Post\StorePostRequest;
use App\Http\Requests\Post\UpdatePostRequest;
use App\Http\Resources\PostCollection;
use App\Http\Resources\PostResource;
use App\Models\Post;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(): JsonResponse
    {
        $postCollection = new PostCollection(Post::paginate(20));

        return response()->json([
            'success' => true,
            'message' => 'Posts indexed successfully.',
            'data' => $postCollection
        ], 200);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StorePostRequest $request): JsonResponse
    {
        $validated = $request->validated();

        $validated['user_id'] = Auth::id();

        $postResource = new PostResource(Post::create($validated));

        return response()->json([
            'success' => true,
            'message' => 'Post created successfully.',
            'data' => [
                'post' => $postResource
            ]
        ], 201);
    }

    /**
     * Display the specified resource.
     */
    public function show(Post $post): JsonResponse
    {
        $postResource = new PostResource($post);

        return response()->json([
            'success' => true,
            'message' => 'Post found successfully.',
            'data' => $postResource
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdatePostRequest $request, Post $post)
    {
        $validated = $request->validated();

        if (Auth::user()['id'] !== $post['user_id']) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized.'
            ], 401);
        }

        $validated['image_url'] = $request->file('image')->store('public/images');
        unset($validated['image']);

        $post->update($validated);

        $postResource = new PostResource($post);

        return response()->json([
            'success' => true,
            'message' => 'Post updated successfully.',
            'data' => [
                'post' => $postResource
            ]
        ]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Post $post): JsonResponse
    {
        if (Auth::user()['id'] !== $post['user_id']) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized.'
            ], 401);
        }

        $post->delete();

        return response()->json([
            'success' => true,
            'message' => 'Post removed successfully.',
        ]);
    }
}
