<?php

namespace App\Rating\Entity;

use App\Auth\Entity\User;
use Doctrine\ORM\Mapping as ORM;
use App\Rating\Repository\LikeRepository;
use Symfony\Component\Uid\Uuid;

#[ORM\Entity(repositoryClass: LikeRepository::class)]
#[ORM\Table(name: 'likes')]
#[ORM\UniqueConstraint(name: 'idx_likes_user_comment', columns: ['user_id', 'comment_id'])]
class Like
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private ?int $id = null;

    #[ORM\Column(type: 'string', length: 36, unique: true)]
    private string $uuid;

    #[ORM\ManyToOne(targetEntity: User::class)]
    #[ORM\JoinColumn(name: 'user_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')]
    private User $user;

    #[ORM\ManyToOne(targetEntity: Comment::class, inversedBy: 'likes')]
    #[ORM\JoinColumn(name: 'comment_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')]
    private Comment $comment;

    /** 1 = like, -1 = dislike */
    #[ORM\Column(type: 'smallint')]
    private int $value;

    #[ORM\Column(name: 'created_at', type: 'integer')]
    private int $createdAt;

    public function __construct(User $user, Comment $comment, int $value)
    {
        $this->uuid      = Uuid::v4()->toRfc4122();
        $this->user      = $user;
        $this->comment   = $comment;
        $this->value     = $value >= 0 ? 1 : -1;
        $this->createdAt = time();
    }

    public function getId(): ?int       { return $this->id; }
    public function getUuid(): string   { return $this->uuid; }
    public function getUser(): User     { return $this->user; }
    public function getComment(): Comment { return $this->comment; }
    public function getValue(): int     { return $this->value; }

    public function setValue(int $v): self { $this->value = $v >= 0 ? 1 : -1; return $this; }

    public function toArray(): array
    {
        return [
            'uuid'        => $this->uuid,
            'comment_uuid' => $this->comment->getUuid(),
            'user_uuid'   => $this->user->getUuid(),
            'value'       => $this->value,
            'created_at'  => $this->createdAt,
        ];
    }
}
