<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\KnowledgeBaseQuestion;
use App\Models\KnowledgeBaseAnswer;
use App\Services\KnowledgeBaseService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

/**
 * KnowledgeBaseAnswerApiController
 *
 * AJAX endpoints for knowledge base answer CRUD, helpful votes, and accept.
 */
class KnowledgeBaseAnswerApiController extends Controller
{
    public function __construct(
        protected KnowledgeBaseService $knowledgeBaseService
    ) {}

    /**
     * Store a new answer via AJAX.
     */
    public function store(Request $request, KnowledgeBaseQuestion $question): JsonResponse
    {
        if (!auth()->check() || !auth()->user()->can('answer knowledge base questions')) {
            return response()->json(['success' => false, 'message' => 'Unauthorized.'], 403);
        }

        abort_if(!$question->is_published, 404);

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

        $answer = $this->knowledgeBaseService->createAnswer($question, $validated, auth()->user());

        return response()->json([
            'success' => true,
            'data'    => [
                'id'           => $answer->id,
                'content'      => $answer->content,
                'author'       => $answer->user->name,
                'avatar'       => $answer->user->avatar ?? null,
                'time_ago'     => $answer->created_at->diffForHumans(),
                'is_accepted'  => false,
                'helpful_count'=> 0,
                'answer_count' => $question->fresh()->answer_count,
            ],
            'message' => 'Answer submitted successfully!',
        ]);
    }

    /**
     * Update an answer via AJAX.
     */
    public function update(Request $request, KnowledgeBaseQuestion $question, KnowledgeBaseAnswer $answer): JsonResponse
    {
        if (!auth()->check()) {
            return response()->json(['success' => false, 'message' => 'Unauthorized.'], 401);
        }

        if ($answer->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:20|max:10000',
        ]);

        $this->knowledgeBaseService->updateAnswer($answer, $validated);

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

    /**
     * Delete an answer via AJAX.
     */
    public function destroy(KnowledgeBaseQuestion $question, KnowledgeBaseAnswer $answer): JsonResponse
    {
        if (!auth()->check()) {
            return response()->json(['success' => false, 'message' => 'Unauthorized.'], 401);
        }

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

        $this->knowledgeBaseService->deleteAnswer($answer);

        return response()->json([
            'success'      => true,
            'answer_count' => $question->fresh()->answer_count,
            'message'      => 'Answer deleted.',
        ]);
    }

    /**
     * Toggle helpful vote on an answer.
     */
    public function toggleHelpful(Request $request, KnowledgeBaseAnswer $answer): JsonResponse
    {
        if (!auth()->check()) {
            return response()->json(['success' => false, 'message' => 'Login to vote.'], 401);
        }

        $alreadyVoted = DB::table('answer_helpful_votes')
            ->where('answer_id', $answer->id)
            ->where('user_id', auth()->id())
            ->exists();

        if ($alreadyVoted) {
            DB::table('answer_helpful_votes')
                ->where('answer_id', $answer->id)
                ->where('user_id', auth()->id())
                ->delete();
            $answer->decrement('helpful_count');
            $isHelpful = false;
        } else {
            DB::table('answer_helpful_votes')->insert([
                'answer_id'  => $answer->id,
                'user_id'    => auth()->id(),
                'created_at' => now(),
            ]);
            $answer->increment('helpful_count');
            $isHelpful = true;
        }

        return response()->json([
            'success' => true,
            'data'    => [
                'is_helpful'    => $isHelpful,
                'helpful_count' => $answer->fresh()->helpful_count,
            ],
            'message' => $isHelpful ? 'Marked as helpful!' : 'Removed helpful vote.',
        ]);
    }
}
