<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Post;
use App\Models\Vote;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PostVoteController extends Controller
{
    public function toggle(Request $request, Post $post)
    {
        $request->validate([
            'type' => 'required|in:upvote,downvote'
        ]);

        $user = $request->user();
        $type = $request->type;

        DB::transaction(function () use ($user, $post, $type) {
            $existingVote = Vote::where('post_id', $post->id)
                ->where('user_id', $user->id)
                ->first();

            if ($existingVote) {
                if ($existingVote->type === $type) {
                    // Toggle Off (Remove vote)
                    $existingVote->delete();
                    $post->decrement("{$type}s_count");
                } else {
                    // Switch Vote (e.g., upvote to downvote)
                    $oldType = $existingVote->type;
                    $existingVote->update(['type' => $type]);
                    
                    $post->decrement("{$oldType}s_count");
                    $post->increment("{$type}s_count");
                }
            } else {
                // New Vote
                Vote::create([
                    'user_id' => $user->id,
                    'post_id' => $post->id,
                    'type' => $type
                ]);
                $post->increment("{$type}s_count");
            }
        });

        // Return fresh counts
        return response()->json([
            'upvotes_count' => $post->fresh()->upvotes_count,
            'downvotes_count' => $post->fresh()->downvotes_count,
            'user_vote' => Vote::where('post_id', $post->id)->where('user_id', $user->id)->value('type')
        ]);
    }
}