<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Ferienpass\CoreBundle\Repository\BookEntryRepository;
use Symfony\Bridge\Doctrine\Types\UuidType;
use Symfony\Component\Uid\Uuid;

#[ORM\Entity(repositoryClass: BookEntryRepository::class)]
class BookEntry
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer', options: ['unsigned' => true])]
    private ?int $id = null;

    #[ORM\Column(type: UuidType::NAME)]
    private Uuid $uuid;

    #[ORM\Column(type: 'datetime_immutable', options: ['default' => 'CURRENT_TIMESTAMP'])]
    private \DateTimeInterface $bookingDate;

    #[ORM\ManyToOne(targetEntity: Payment::class, inversedBy: 'bookEntries')]
    private ?Payment $payment = null;

    #[ORM\Column(type: 'string', length: 64, nullable: false)]
    private string $type;

    #[ORM\Column(type: 'string', length: 255, nullable: false)]
    private string $postingRecord;

    public function __construct(#[ORM\Column(type: 'integer', options: ['unsigned' => false])]
        private int $value, #[ORM\ManyToOne(targetEntity: Debtor::class, inversedBy: 'bookEntries')]
        private Debtor $debtor, ?Payment $payment = null, ?string $type = null, ?string $postingRecord = null)
    {
        $this->uuid = Uuid::v7();

        if (null === $type && $payment instanceof Payment) {
            $type = 'payment';
        }

        if (null === $type) {
            $type = 'manual';
        }

        if (!\in_array($type, ['manual', 'payment'], true)) {
            throw new \InvalidArgumentException('Book entry type must be one of: "manual", "payment"');
        }

        $this->bookingDate = new \DateTimeImmutable();
        $this->payment = $payment;
        $this->postingRecord = $postingRecord ?? '';
        $this->type = $type;
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getUuid(): Uuid
    {
        return $this->uuid;
    }

    public function getBookingDate(): \DateTimeInterface
    {
        return $this->bookingDate;
    }

    public function getValue(): int
    {
        return $this->value;
    }

    public function getDebtor(): ?Debtor
    {
        return $this->debtor;
    }

    public function getPayment(): ?Payment
    {
        return $this->payment;
    }

    public function getType(): string
    {
        return $this->type;
    }

    public function getPostingRecord(): string
    {
        return $this->postingRecord;
    }

    public function isPayment(): bool
    {
        return 'payment' === $this->type;
    }
}
