<?php

namespace App\Models;

use App\Core\Model;

class Vote extends Model
{
    protected string $table = 'votes';

    public function vote(int $userId, ?int $postId, ?int $commentId, int $type): array
    {
        // Check existing
        $stmt = $this->db->prepare(
            "SELECT * FROM votes WHERE user_id = ? AND post_id <=> ? AND comment_id <=> ?"
        );
        $stmt->execute([$userId, $postId, $commentId]);
        $existing = $stmt->fetch();

        if ($existing) {
            if ($existing['vote_type'] == $type) {
                $this->db->prepare("DELETE FROM votes WHERE id = ?")->execute([$existing['id']]);
            } else {
                $this->db->prepare("UPDATE votes SET vote_type = ? WHERE id = ?")->execute([$type, $existing['id']]);
            }
        } else {
            $this->db->prepare(
                "INSERT INTO votes (user_id, post_id, comment_id, vote_type) VALUES (?, ?, ?, ?)"
            )->execute([$userId, $postId, $commentId, $type]);
        }

        // Return updated score
        if ($postId) {
            $stmt = $this->db->prepare("SELECT COALESCE(SUM(vote_type), 0) FROM votes WHERE post_id = ?");
            $stmt->execute([$postId]);
        } else {
            $stmt = $this->db->prepare("SELECT COALESCE(SUM(vote_type), 0) FROM votes WHERE comment_id = ?");
            $stmt->execute([$commentId]);
        }
        return ['score' => (int)$stmt->fetchColumn()];
    }
}
