<?php

declare(strict_types=1);

namespace App\Entity;

use App\Repository\TenantDomainRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;

#[ORM\Entity(repositoryClass: TenantDomainRepository::class)]
#[ORM\Table(name: 'tenant_domains')]
#[ORM\HasLifecycleCallbacks]
#[UniqueEntity(fields: ['host'], message: 'Ce domaine est déjà associé à une madrassa.')]
class TenantDomain
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\ManyToOne(inversedBy: 'tenantDomains')]
    #[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
    private ?Ecole $ecole = null;

    #[ORM\Column(length: 255, unique: true)]
    #[Assert\NotBlank(message: 'Le domaine est obligatoire.')]
    #[Assert\Length(max: 255)]
    #[Assert\Regex(pattern: '/^[a-z0-9.-]+$/', message: 'Saisissez uniquement le host, sans protocole ni chemin.')]
    private ?string $host = null;

    #[ORM\Column(options: ['default' => false])]
    private bool $canonical = false;

    #[ORM\Column(options: ['default' => true])]
    private bool $active = true;

    #[ORM\Column(type: Types::DATETIME_IMMUTABLE)]
    private ?\DateTimeImmutable $createdAt = null;

    #[ORM\Column(type: Types::DATETIME_IMMUTABLE)]
    private ?\DateTimeImmutable $updatedAt = null;

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

    public function getEcole(): ?Ecole
    {
        return $this->ecole;
    }

    public function setEcole(?Ecole $ecole): static
    {
        $this->ecole = $ecole;

        return $this;
    }

    public function getHost(): ?string
    {
        return $this->host;
    }

    public function setHost(string $host): static
    {
        $this->host = self::normalizeHost($host);

        return $this;
    }

    public function isCanonical(): bool
    {
        return $this->canonical;
    }

    public function setCanonical(bool $canonical): static
    {
        $this->canonical = $canonical;

        return $this;
    }

    public function isActive(): bool
    {
        return $this->active;
    }

    public function setActive(bool $active): static
    {
        $this->active = $active;

        return $this;
    }

    public function getCreatedAt(): ?\DateTimeImmutable
    {
        return $this->createdAt;
    }

    public function getUpdatedAt(): ?\DateTimeImmutable
    {
        return $this->updatedAt;
    }

    #[ORM\PrePersist]
    public function initializeTimestamps(): void
    {
        $now = new \DateTimeImmutable();
        $this->createdAt ??= $now;
        $this->updatedAt = $now;
    }

    #[ORM\PreUpdate]
    public function refreshUpdatedAt(): void
    {
        $this->updatedAt = new \DateTimeImmutable();
    }

    public static function normalizeHost(string $host): string
    {
        $host = mb_strtolower(trim($host));
        $host = preg_replace('#^https?://#', '', $host) ?: $host;
        $host = explode('/', $host, 2)[0];

        if (str_contains($host, ':') && !str_contains($host, ']')) {
            $host = explode(':', $host, 2)[0];
        }

        return trim($host, '.');
    }
}
