<?php

namespace App\Http\Controllers\Api;

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

/**
 * DiscussionApiController
 * 
 * Handles API endpoints for discussion interactions.
 * Provides AJAX endpoints for likes, bookmarks, and other interactions.
 * 
 * @package App\Http\Controllers\Api
 */
class DiscussionApiController extends Controller
{
    /**
     * Create a new controller instance.
     */
    public function __construct(
        protected DiscussionService $discussionService
    ) {}

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

        $discussions = $this->discussionService->getPublicDiscussions($filters, 15);

        return response()->json([
            'success' => true,
            'data' => $discussions->map(function ($discussion) {
                return [
                    'id' => $discussion->id,
                    'title' => $discussion->title,
                    'slug' => $discussion->slug,
                    'excerpt' => $discussion->excerpt,
                    'author' => [
                        'id' => $discussion->user->id,
                        'name' => $discussion->user->name,
                        'avatar' => $discussion->user->avatar ?? null,
                    ],
                    'topic' => $discussion->topic ? [
                        'id' => $discussion->topic->id,
                        'name' => $discussion->topic->name,
                        'slug' => $discussion->topic->slug,
                    ] : null,
                    'stats' => [
                        'views' => $discussion->view_count,
                        'replies' => $discussion->active_replies_count ?? 0,
                    ],
                    'is_featured' => $discussion->is_featured,
                    'is_pinned' => $discussion->is_pinned,
                    'created_at' => $discussion->created_at->toISOString(),
                    'last_activity_at' => $discussion->last_activity_at?->toISOString(),
                    'url' => route('public.discussions.show', $discussion->slug),
                ];
            }),
            'meta' => [
                'current_page' => $discussions->currentPage(),
                'last_page' => $discussions->lastPage(),
                'per_page' => $discussions->perPage(),
                'total' => $discussions->total(),
            ],
        ]);
    }

    /**
     * Toggle like on a discussion.
     *
     * @param \Illuminate\Http\Request $request
     * @param \App\Models\Discussion $discussion
     * @return \Illuminate\Http\JsonResponse
     */
    public function toggleLike(Request $request, Discussion $discussion): JsonResponse
    {
        $user = auth()->user();

        // Check if already liked
        $existingLike = ContentInteraction::where([
            'user_id' => $user->id,
            'interactable_type' => Discussion::class,
            'interactable_id' => $discussion->id,
            'interaction_type' => 'like',
        ])->first();

        if ($existingLike) {
            // Unlike
            $existingLike->delete();
            $isLiked = false;
        } else {
            // Like
            ContentInteraction::create([
                'user_id' => $user->id,
                'interactable_type' => Discussion::class,
                'interactable_id' => $discussion->id,
                'interaction_type' => 'like',
            ]);
            $isLiked = true;
        }

        // Get updated count
        $likeCount = ContentInteraction::where([
            'interactable_type' => Discussion::class,
            'interactable_id' => $discussion->id,
            'interaction_type' => 'like',
        ])->count();

        return response()->json([
            'success' => true,
            'data' => [
                'is_liked' => $isLiked,
                'like_count' => $likeCount,
            ],
            'message' => $isLiked ? 'Discussion liked!' : 'Discussion unliked.',
        ]);
    }

    /**
     * Toggle bookmark on a discussion.
     *
     * @param \Illuminate\Http\Request $request
     * @param \App\Models\Discussion $discussion
     * @return \Illuminate\Http\JsonResponse
     */
    public function toggleBookmark(Request $request, Discussion $discussion): JsonResponse
    {
        $user = auth()->user();

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

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

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

    /**
     * Get user's bookmarked discussions.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bookmarks(Request $request): JsonResponse
    {
        $user = auth()->user();

        $bookmarks = ContentInteraction::where([
            'user_id' => $user->id,
            'interaction_type' => 'bookmark',
        ])
            ->where('interactable_type', Discussion::class)
            ->with('interactable.user', 'interactable.topic')
            ->latest()
            ->paginate(15);

        return response()->json([
            'success' => true,
            'data' => $bookmarks->map(function ($bookmark) {
                $discussion = $bookmark->interactable;
                return [
                    'id' => $discussion->id,
                    'title' => $discussion->title,
                    'slug' => $discussion->slug,
                    'bookmarked_at' => $bookmark->created_at->toISOString(),
                    'url' => route('public.discussions.show', $discussion->slug),
                ];
            }),
            'meta' => [
                'current_page' => $bookmarks->currentPage(),
                'last_page' => $bookmarks->lastPage(),
                'total' => $bookmarks->total(),
            ],
        ]);
    }

    /**
     * Get user's liked discussions.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function likes(Request $request): JsonResponse
    {
        $user = auth()->user();

        $likes = ContentInteraction::where([
            'user_id' => $user->id,
            'interaction_type' => 'like',
        ])
            ->where('interactable_type', Discussion::class)
            ->with('interactable.user', 'interactable.topic')
            ->latest()
            ->paginate(15);

        return response()->json([
            'success' => true,
            'data' => $likes->map(function ($like) {
                $discussion = $like->interactable;
                return [
                    'id' => $discussion->id,
                    'title' => $discussion->title,
                    'slug' => $discussion->slug,
                    'liked_at' => $like->created_at->toISOString(),
                    'url' => route('public.discussions.show', $discussion->slug),
                ];
            }),
            'meta' => [
                'current_page' => $likes->currentPage(),
                'last_page' => $likes->lastPage(),
                'total' => $likes->total(),
            ],
        ]);
    }
}
