<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\CoreBundle\Seed\Entity;

use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Serenity\CoreBundle\Seed\Doctrine\Repository\SeedStateRepository;
use Serenity\CoreBundle\Shared\Aggregate\AggregateRoot;
use Serenity\CoreBundle\Shared\Aggregate\AggregateRootInterface;
use Serenity\CoreBundle\Shared\Common\IdentifierTrait;
use Serenity\CoreBundle\Shared\Common\TimestampTrait;
use Serenity\CoreBundle\Shared\Feature\SerenitySaasTrait;
use Symfony\Bridge\Doctrine\Types\UuidType;
use Symfony\Component\Uid\Uuid;

#[ORM\Entity(repositoryClass: SeedStateRepository::class)]
#[ORM\Table(name: 'serenity_core_seed_state')]
#[ORM\UniqueConstraint(
    name: 'uniq_serenity_seed_state_saas_seed',
    columns: ['saasidentifier', 'seedname'],
    options: ['nulls_not_distinct' => true]
)]
#[ORM\Index(name: 'idx_serenity_seed_state_saas', columns: ['saasidentifier'])]
#[ORM\HasLifecycleCallbacks]
class SeedState implements AggregateRootInterface
{
    use AggregateRoot;
    use IdentifierTrait {
        IdentifierTrait::__construct as private identifierConstruct;
    }
    use SerenitySaasTrait;
    use TimestampTrait;

    #[ORM\Column(type: Types::STRING, length: 80)]
    public private(set) string $seedName;

    #[ORM\Column(type: Types::INTEGER, options: ['default' => 0])]
    public private(set) int $version = 0;

    #[ORM\Column(type: UuidType::NAME, unique: true)]
    public private(set) Uuid $runId;

    public function __construct()
    {
        $this->identifierConstruct();
    }

    public static function create(
        ?string $saasIdentifier,
        string $seedName,
        Uuid $runId,
        int $version = 0,
    ): self {
        $self = new self();
        $self->saasIdentifier = $saasIdentifier;
        $self->runId = $runId;
        $self->seedName = $seedName;
        $self->version = $version;

        return $self;
    }

    public function moveTo(int $newVersion, Uuid $runId): void
    {
        $this->version = $newVersion;
        $this->runId = $runId;
    }
}
