<?php

namespace App\Http\Controllers\Member;

use App\Http\Controllers\Controller;
use App\Http\Requests\Member\RateReplyRequest;
use App\Http\Requests\Member\StoreForumPostRequest;
use App\Http\Requests\Member\StoreForumReplyRequest;
use App\Models\ForumPost;
use App\Models\ForumReply;
use App\Services\Member\ForumService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

// ══════════════════════════════════════════════════════════════════
//  InPractice — Member\ForumController
//  Location: app/Http/Controllers/Member/ForumController.php
//
//  Thin controller — follows the Project Bible strictly.
//  Every method: receive → call service → return response.
//  Zero business logic here.
//
//  Routes:
//    GET    /app/forum                    index
//    GET    /app/forum/create             create
//    POST   /app/forum                    store
//    GET    /app/forum/{post}             show
//    PATCH  /app/forum/{post}             update
//    DELETE /app/forum/{post}             destroy
//    PATCH  /app/forum/{post}/close       close
//    POST   /app/forum/{post}/replies     storeReply
//    PATCH  /app/forum/{post}/replies/{reply}   updateReply
//    DELETE /app/forum/{post}/replies/{reply}   destroyReply
//    POST   /app/forum/{post}/like        likePost      → JSON
//    POST   /app/forum/{post}/replies/{reply}/like  likeReply → JSON
//    PATCH  /app/forum/{post}/replies/{reply}/rate  rateReply → JSON
//    PATCH  /app/forum/{post}/best-answer/{reply}   markBestAnswer → JSON
// ══════════════════════════════════════════════════════════════════

class ForumController extends Controller
{
    public function __construct(
        private readonly ForumService $forumService
    ) {}

    /**
     * Forum feed — all posts, filtered and paginated.
     * GET /app/forum
     */
    public function index(Request $request): Response
    {
        $data = $this->forumService->index(
            $request->user(),
            $request->only(['hub_id', 'status', 'sort', 'search'])
        );

        return Inertia::render('Member/Forum/Index', $data);
    }

    /**
     * Create post form.
     * GET /app/forum/create
     */
    public function create(): Response
    {
        return Inertia::render('Member/Forum/Create', $this->forumService->createFormData());
    }

    /**
     * Store new post.
     * POST /app/forum
     */
    public function store(StoreForumPostRequest $request): RedirectResponse
    {
        $post = $this->forumService->createPost($request->user(), $request->validated());

        return redirect()->route('member.forum.show', $post->id)
                         ->with('success', __('forum.post_created'));
    }

    /**
     * Full post with replies.
     * GET /app/forum/{post}
     */
    public function show(ForumPost $post): Response
    {
        $data = $this->forumService->show(auth()->user(), $post);

        return Inertia::render('Member/Forum/Show', $data);
    }

    /**
     * Update own post.
     * PATCH /app/forum/{post}
     */
    public function update(StoreForumPostRequest $request, ForumPost $post): RedirectResponse
    {
        $this->forumService->updatePost($request->user(), $post, $request->validated());

        return redirect()->route('member.forum.show', $post->id)
                         ->with('success', __('forum.post_updated'));
    }

    /**
     * Delete own post.
     * DELETE /app/forum/{post}
     */
    public function destroy(Request $request, ForumPost $post): RedirectResponse
    {
        $this->forumService->deletePost($request->user(), $post);

        return redirect()->route('member.forum.index')
                         ->with('success', __('forum.post_deleted'));
    }

    /**
     * Close thread — post owner only.
     * PATCH /app/forum/{post}/close
     */
    public function close(Request $request, ForumPost $post): JsonResponse
    {
        $this->forumService->closePost($request->user(), $post);

        return response()->json(['status' => 'closed']);
    }

    /**
     * Post a reply.
     * POST /app/forum/{post}/replies
     */
    public function storeReply(StoreForumReplyRequest $request, ForumPost $post): JsonResponse
    {
        $reply = $this->forumService->createReply($request->user(), $post, $request->validated());

        return response()->json(['reply' => $reply], 201);
    }

    /**
     * Update own reply.
     * PATCH /app/forum/{post}/replies/{reply}
     */
    public function updateReply(StoreForumReplyRequest $request, ForumPost $post, ForumReply $reply): JsonResponse
    {
            $updated = $this->forumService->updateReply($request->user(), $reply, $request->validated('body'));

            return response()->json(['reply' => $updated]);
    }

    /**
     * Delete own reply.
     * DELETE /app/forum/{post}/replies/{reply}
     */
    public function destroyReply(Request $request, ForumPost $post, ForumReply $reply): JsonResponse
    {
        $this->forumService->deleteReply($request->user(), $reply);

        return response()->json(['deleted' => true]);
    }

    /**
     * Toggle like on a post — JSON, no page reload.
     * POST /app/forum/{post}/like
     */
    public function likePost(Request $request, ForumPost $post): JsonResponse
    {
        $result = $this->forumService->likePost($request->user(), $post);

        return response()->json($result);
    }

    /**
     * Toggle like on a reply — JSON, no page reload.
     * POST /app/forum/{post}/replies/{reply}/like
     */
    public function likeReply(Request $request, ForumPost $post, ForumReply $reply): JsonResponse
    {
        $result = $this->forumService->likeReply($request->user(), $reply);

        return response()->json($result);
    }

    /**
     * Rate a reply 1–5 — JSON, no page reload.
     * PATCH /app/forum/{post}/replies/{reply}/rate
     */
    public function rateReply(RateReplyRequest $request, ForumPost $post, ForumReply $reply): JsonResponse
    {
        $result = $this->forumService->rateReply(
            $request->user(),
            $reply,
            (int) $request->validated()['rating']
        );

        return response()->json($result);
    }

    /**
     * Mark best answer — post owner only — JSON, no page reload.
     * PATCH /app/forum/{post}/best-answer/{reply}
     */
    public function markBestAnswer(Request $request, ForumPost $post, ForumReply $reply): JsonResponse
    {
        $this->forumService->markBestAnswer($request->user(), $post, $reply);

        return response()->json(['is_best_answer' => true]);
    }
}
