<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\KnowledgeBaseQuestion;
use App\Models\KnowledgeBaseAnswer;
use App\Models\ContentInteraction;
use App\Services\KnowledgeBaseService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

/**
 * KnowledgeBaseApiController
 * 
 * Handles API endpoints for knowledge base interactions.
 * Provides AJAX endpoints for marking answers helpful, accepting answers, etc.
 * 
 * @package App\Http\Controllers\Api
 */
class KnowledgeBaseApiController extends Controller
{
    /**
     * Create a new controller instance.
     */
    public function __construct(
        protected KnowledgeBaseService $knowledgeBaseService
    ) {}

    /**
     * Get a list of knowledge base questions for API consumption.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request): JsonResponse
    {
        $filters = [
            'category_id' => $request->get('category_id'),
            'search' => $request->get('search'),
            'difficulty' => $request->get('difficulty'),
            'sort' => $request->get('sort', 'latest'),
        ];

        $questions = $this->knowledgeBaseService->getPublicQuestions($filters, 15);

        return response()->json([
            'success' => true,
            'data' => $questions->map(function ($question) {
                return [
                    'id' => $question->id,
                    'title' => $question->title,
                    'slug' => $question->slug,
                    'excerpt' => $question->excerpt,
                    'author' => [
                        'id' => $question->user->id,
                        'name' => $question->user->name,
                        'avatar' => $question->user->avatar ?? null,
                    ],
                    'category' => $question->category ? [
                        'id' => $question->category->id,
                        'name' => $question->category->name,
                        'slug' => $question->category->slug,
                    ] : null,
                    'stats' => [
                        'views' => $question->view_count,
                        'answers' => $question->answers_count ?? 0,
                        'helpful' => $question->helpful_count ?? 0,
                    ],
                    'difficulty' => $question->difficulty,
                    'is_featured' => $question->is_featured,
                    'created_at' => $question->created_at->toISOString(),
                    'url' => route('public.knowledge-base.show', $question->slug),
                ];
            }),
            'meta' => [
                'current_page' => $questions->currentPage(),
                'last_page' => $questions->lastPage(),
                'per_page' => $questions->perPage(),
                'total' => $questions->total(),
            ],
        ]);
    }

    /**
     * Mark a question as helpful.
     *
     * @param \Illuminate\Http\Request $request
     * @param \App\Models\KnowledgeBaseQuestion $question
     * @return \Illuminate\Http\JsonResponse
     */
    public function markHelpful(Request $request, KnowledgeBaseQuestion $question): JsonResponse
    {
        $user = auth()->user();
        $identifier = $user ? 'user_' . $user->id : 'ip_' . $request->ip();

        // Check if already marked helpful
        $existingHelpful = ContentInteraction::where([
            'user_id' => $user->id ?? null,
            'interactable_type' => KnowledgeBaseQuestion::class,
            'interactable_id' => $question->id,
            'interaction_type' => 'helpful',
        ])->when(!$user, function ($query) use ($request) {
            $query->where('metadata->ip', $request->ip());
        })->first();

        if ($existingHelpful) {
            // Remove helpful
            $existingHelpful->delete();
            $isHelpful = false;
        } else {
            // Mark helpful
            ContentInteraction::create([
                'user_id' => $user->id ?? null,
                'interactable_type' => KnowledgeBaseQuestion::class,
                'interactable_id' => $question->id,
                'interaction_type' => 'helpful',
                'metadata' => [
                    'ip' => $request->ip(),
                    'user_agent' => $request->userAgent(),
                ],
            ]);
            $isHelpful = true;
        }

        // Get updated count
        $helpfulCount = ContentInteraction::where([
            'interactable_type' => KnowledgeBaseQuestion::class,
            'interactable_id' => $question->id,
            'interaction_type' => 'helpful',
        ])->count();

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

    /**
     * Accept an answer as the correct solution.
     *
     * @param \Illuminate\Http\Request $request
     * @param \App\Models\KnowledgeBaseAnswer $answer
     * @return \Illuminate\Http\JsonResponse
     */
    public function acceptAnswer(Request $request, KnowledgeBaseAnswer $answer): JsonResponse
    {
        $user = auth()->user();
        $question = $answer->question;

        // Check permission - only question owner or managers can accept
        if ($question->user_id !== $user->id && !$user->can('accept knowledge base answers')) {
            return response()->json([
                'success' => false,
                'message' => 'You do not have permission to accept this answer.',
            ], 403);
        }

        // Unaccept any previously accepted answers
        KnowledgeBaseAnswer::where('question_id', $question->id)
            ->where('is_accepted', true)
            ->update(['is_accepted' => false]);

        // Accept this answer
        $answer->update(['is_accepted' => true]);

        return response()->json([
            'success' => true,
            'data' => [
                'answer_id' => $answer->id,
                'is_accepted' => true,
            ],
            'message' => 'Answer accepted as the correct solution!',
        ]);
    }

    /**
     * Vote on an answer (upvote/downvote).
     *
     * @param \Illuminate\Http\Request $request
     * @param \App\Models\KnowledgeBaseAnswer $answer
     * @return \Illuminate\Http\JsonResponse
     */
    public function voteAnswer(Request $request, KnowledgeBaseAnswer $answer): JsonResponse
    {
        $request->validate([
            'vote' => 'required|in:up,down,none',
        ]);

        $user = auth()->user();
        $vote = $request->vote;

        // Check for existing vote
        $existingVote = ContentInteraction::where([
            'user_id' => $user->id,
            'interactable_type' => KnowledgeBaseAnswer::class,
            'interactable_id' => $answer->id,
            'interaction_type' => 'vote',
        ])->first();

        if ($vote === 'none') {
            // Remove vote
            if ($existingVote) {
                $existingVote->delete();
            }
            $currentVote = null;
        } else {
            // Create or update vote
            ContentInteraction::updateOrCreate(
                [
                    'user_id' => $user->id,
                    'interactable_type' => KnowledgeBaseAnswer::class,
                    'interactable_id' => $answer->id,
                    'interaction_type' => 'vote',
                ],
                [
                    'metadata' => ['vote_type' => $vote],
                ]
            );
            $currentVote = $vote;
        }

        // Calculate vote counts
        $upvotes = ContentInteraction::where([
            'interactable_type' => KnowledgeBaseAnswer::class,
            'interactable_id' => $answer->id,
            'interaction_type' => 'vote',
        ])->where('metadata->vote_type', 'up')->count();

        $downvotes = ContentInteraction::where([
            'interactable_type' => KnowledgeBaseAnswer::class,
            'interactable_id' => $answer->id,
            'interaction_type' => 'vote',
        ])->where('metadata->vote_type', 'down')->count();

        return response()->json([
            'success' => true,
            'data' => [
                'current_vote' => $currentVote,
                'upvotes' => $upvotes,
                'downvotes' => $downvotes,
                'score' => $upvotes - $downvotes,
            ],
        ]);
    }

    /**
     * Bookmark a question.
     *
     * @param \Illuminate\Http\Request $request
     * @param \App\Models\KnowledgeBaseQuestion $question
     * @return \Illuminate\Http\JsonResponse
     */
    public function toggleBookmark(Request $request, KnowledgeBaseQuestion $question): JsonResponse
    {
        $user = auth()->user();

        // Check if already bookmarked
        $existingBookmark = ContentInteraction::where([
            'user_id' => $user->id,
            'interactable_type' => KnowledgeBaseQuestion::class,
            'interactable_id' => $question->id,
            'interaction_type' => 'bookmark',
        ])->first();

        if ($existingBookmark) {
            // Remove bookmark
            $existingBookmark->delete();
            $isBookmarked = false;
        } else {
            // Add bookmark
            ContentInteraction::create([
                'user_id' => $user->id,
                'interactable_type' => KnowledgeBaseQuestion::class,
                'interactable_id' => $question->id,
                'interaction_type' => 'bookmark',
            ]);
            $isBookmarked = true;
        }

        return response()->json([
            'success' => true,
            'data' => [
                'is_bookmarked' => $isBookmarked,
            ],
            'message' => $isBookmarked ? 'Question bookmarked!' : 'Bookmark removed.',
        ]);
    }

    /**
     * Get related questions.
     *
     * @param \Illuminate\Http\Request $request
     * @param \App\Models\KnowledgeBaseQuestion $question
     * @return \Illuminate\Http\JsonResponse
     */
    public function related(Request $request, KnowledgeBaseQuestion $question): JsonResponse
    {
        $relatedQuestions = KnowledgeBaseQuestion::query()
            ->published()
            ->where('id', '!=', $question->id)
            ->when($question->category_id, function ($query) use ($question) {
                $query->where('category_id', $question->category_id);
            })
            ->orWhereHas('tags', function ($query) use ($question) {
                $query->whereIn('tags.id', $question->tags->pluck('id'));
            })
            ->with('category', 'user')
            ->limit(5)
            ->get();

        return response()->json([
            'success' => true,
            'data' => $relatedQuestions->map(function ($q) {
                return [
                    'id' => $q->id,
                    'title' => $q->title,
                    'slug' => $q->slug,
                    'category' => $q->category ? [
                        'name' => $q->category->name,
                        'slug' => $q->category->slug,
                    ] : null,
                    'url' => route('public.knowledge-base.show', $q->slug),
                ];
            }),
        ]);
    }
}
