<?php

namespace App\Http\Controllers\Forum;

use App\Http\Controllers\Controller;
use App\Http\Requests\Forum\StorePostRequest;
use App\Http\Requests\Forum\VotePostRequest;
use App\Models\ForumPost;
use App\Models\ForumThread;
use App\Notifications\Forum\PostReply;
use App\Notifications\Forum\PostUpvoted;
use Illuminate\Http\RedirectResponse;

class PostController extends Controller
{
    /**
     * Store a newly created post (comment) in storage.
     */
    public function store(StorePostRequest $request, ForumThread $thread): RedirectResponse
    {
        $post = $thread->posts()->create([
            'user_id' => auth()->id(),
            'parent_id' => $request->parent_id,
            'content' => $request->content,
        ]);

        // Notify
        if ($post->parent_id) {
            $parent = ForumPost::find($post->parent_id);
            if ($parent && $parent->user_id !== $post->user_id) {
                $parent->user->notify(new PostReply($post));
            }
        } else {
            if ($thread->user_id !== $post->user_id) {
                $thread->user->notify(new PostReply($post));
            }
        }

        return back()->with('success', 'Comentario publicado.');
    }

    /**
     * Handle up/down voting for a post.
     */
    public function vote(VotePostRequest $request, ForumPost $post): RedirectResponse
    {
        // Prevent user from voting on their own post
        if ($post->user_id === auth()->id()) {
            return back()->with('error', 'No puedes votar tu propio comentario.');
        }

        // Check if user already voted
        $existingVote = $post->votes()->where('user_id', auth()->id())->first();

        if ($existingVote) {
            // If clicking same vote type, remove vote (toggle)
            if ($existingVote->vote_type === $request->type) {
                $existingVote->delete();
            } else {
                // Change vote type
                $existingVote->update(['vote_type' => $request->type]);
            }
        } else {
            // Create new vote
            $post->votes()->create([
                'user_id' => auth()->id(),
                'vote_type' => $request->type,
            ]);

            // Notify if upvote (only for new upvotes)
            if ($request->type === 'up') {
                $post->user->notify(new PostUpvoted($post, auth()->user()));
            }
        }

        // Recalculate votes cache
        $post->updateVotesCount();

        return back();
    }
}
