<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Discussion;
use App\Models\DiscussionReply;
use App\Models\ContentInteraction;
use App\Services\DiscussionService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

/**
 * DiscussionReplyApiController
 *
 * AJAX endpoints for discussion reply CRUD and like interactions.
 */
class DiscussionReplyApiController extends Controller
{
    public function __construct(
        protected DiscussionService $discussionService
    ) {}

    /**
     * Store a new reply via AJAX.
     */
    public function store(Request $request, Discussion $discussion): JsonResponse
    {
        if (!auth()->check() || !auth()->user()->can('create discussions')) {
            return response()->json(['success' => false, 'message' => 'Unauthorized.'], 403);
        }

        $validated = $request->validate([
            'content'   => 'required|string|min:10|max:5000',
            'parent_id' => 'nullable|integer|exists:discussion_replies,id',
        ]);

        abort_if(!$discussion->is_active, 404);

        $reply = $this->discussionService->createReply($discussion, $validated, auth()->user());

        $discussion->update([
            'last_activity_at'    => now(),
            'last_reply_user_id'  => auth()->id(),
            'reply_count'         => DiscussionReply::where('discussion_id', $discussion->id)
                                        ->where('is_active', true)->count(),
        ]);

        return response()->json([
            'success' => true,
            'data'    => [
                'id'         => $reply->id,
                'content'    => $reply->content,
                'author'     => $reply->user->name,
                'avatar'     => $reply->user->avatar ?? null,
                'time_ago'   => $reply->created_at->diffForHumans(),
                'depth'      => $reply->depth,
                'parent_id'  => $reply->parent_id,
                'reply_count'=> $discussion->fresh()->reply_count,
            ],
            'message' => 'Reply posted successfully!',
        ]);
    }

    /**
     * Update a reply via AJAX.
     */
    public function update(Request $request, Discussion $discussion, DiscussionReply $reply): JsonResponse
    {
        if (!auth()->check()) {
            return response()->json(['success' => false, 'message' => 'Unauthorized.'], 401);
        }

        if ($reply->user_id !== auth()->id() && !auth()->user()->hasAnyRole(['Manager', 'Super Manager'])) {
            return response()->json(['success' => false, 'message' => 'Forbidden.'], 403);
        }

        $validated = $request->validate([
            'content' => 'required|string|min:10|max:5000',
        ]);

        $this->discussionService->updateReply($reply, $validated);

        return response()->json([
            'success' => true,
            'data'    => ['content' => $reply->fresh()->content],
            'message' => 'Reply updated successfully!',
        ]);
    }

    /**
     * Delete a reply via AJAX.
     */
    public function destroy(Discussion $discussion, DiscussionReply $reply): JsonResponse
    {
        if (!auth()->check()) {
            return response()->json(['success' => false, 'message' => 'Unauthorized.'], 401);
        }

        if ($reply->user_id !== auth()->id() && !auth()->user()->hasAnyRole(['Manager', 'Super Manager'])) {
            return response()->json(['success' => false, 'message' => 'Forbidden.'], 403);
        }

        $this->discussionService->deleteReply($reply);

        $discussion->update([
            'reply_count' => DiscussionReply::where('discussion_id', $discussion->id)
                                ->where('is_active', true)->count(),
        ]);

        return response()->json([
            'success'     => true,
            'reply_count' => $discussion->fresh()->reply_count,
            'message'     => 'Reply deleted.',
        ]);
    }

    /**
     * Toggle like on a reply.
     */
    public function toggleLike(Request $request, DiscussionReply $reply): JsonResponse
    {
        if (!auth()->check()) {
            return response()->json(['success' => false, 'message' => 'Login to like replies.'], 401);
        }

        $existing = ContentInteraction::where([
            'user_id'           => auth()->id(),
            'interactable_type' => DiscussionReply::class,
            'interactable_id'   => $reply->id,
            'interaction_type'  => 'like',
        ])->first();

        if ($existing) {
            $existing->delete();
            $reply->decrement('like_count');
            $isLiked = false;
        } else {
            ContentInteraction::create([
                'user_id'           => auth()->id(),
                'interactable_type' => DiscussionReply::class,
                'interactable_id'   => $reply->id,
                'interaction_type'  => 'like',
            ]);
            $reply->increment('like_count');
            $isLiked = true;
        }

        return response()->json([
            'success'    => true,
            'data'       => [
                'is_liked'   => $isLiked,
                'like_count' => $reply->fresh()->like_count,
            ],
            'message'    => $isLiked ? 'Reply liked!' : 'Like removed.',
        ]);
    }
}
