<?php

namespace App\Blog\Entity;

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

#[ORM\Entity(repositoryClass: BlogRepository::class)]
#[ORM\Table(name: 'blogs')]
#[ORM\Index(columns: ['status', 'created_at'], name: 'idx_blogs_status')]
class Blog
{
    public const STATUS_DRAFT     = 'draft';
    public const STATUS_PUBLISHED = 'published';
    public const STATUS_ARCHIVED  = 'archived';

    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private ?int $id = null;

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

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

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

    #[ORM\Column(type: 'text')]
    private string $body;

    #[ORM\Column(type: 'string', length: 500, nullable: true)]
    private ?string $summary = null;

    #[ORM\Column(type: 'string', length: 500, nullable: true)]
    private ?string $imageUrl = null;

    #[ORM\Column(name: 'image_path', type: 'string', length: 500, nullable: true)]
    private ?string $imagePath = null;

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

    #[ORM\Column(type: 'json')]
    private array $tags = [];

    #[ORM\Column(type: 'string', length: 20)]
    private string $status = self::STATUS_DRAFT;

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

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

    public function __construct(User $author, string $title, string $body)
    {
        $this->uuid      = Uuid::v4()->toRfc4122();
        $this->author    = $author;
        $this->title     = $title;
        $this->slug      = $this->generateSlug($title);
        $this->body      = $body;
        $this->createdAt = time();
        $this->updatedAt = time();
    }

    public function getId(): ?int       { return $this->id; }
    public function getUuid(): string   { return $this->uuid; }
    public function getTitle(): string  { return $this->title; }
    public function getSlug(): string   { return $this->slug; }
    public function getBody(): string   { return $this->body; }
    public function getSummary(): ?string { return $this->summary; }
    public function getImageUrl(): ?string { return $this->imageUrl; }
    public function getImagePath(): ?string { return $this->imagePath; }
    public function getAuthor(): User   { return $this->author; }
    public function getTags(): array    { return $this->tags; }
    public function getStatus(): string { return $this->status; }

    public function setTitle(string $v): self    { $this->title = $v; $this->touch(); return $this; }
    public function setSlug(string $v): self     { $this->slug = $v; $this->touch(); return $this; }
    public function setBody(string $v): self     { $this->body = $v; $this->touch(); return $this; }
    public function setSummary(?string $v): self { $this->summary = $v; $this->touch(); return $this; }
    public function setImageUrl(?string $v): self  { $this->imageUrl = $v; $this->touch(); return $this; }
    public function setImagePath(?string $v): self { $this->imagePath = $v; $this->touch(); return $this; }
    public function setTags(array $v): self      { $this->tags = $v; $this->touch(); return $this; }
    public function setStatus(string $v): self   { $this->status = $v; $this->touch(); return $this; }

    private function touch(): void { $this->updatedAt = time(); }

    private function generateSlug(string $title): string
    {
        $slug = mb_strtolower(trim($title));
        $slug = preg_replace('/\s+/', '-', $slug);
        $slug = preg_replace('/[^a-z0-9\-\p{Arabic}]/u', '', $slug);
        return $slug . '-' . substr(str_replace('-', '', $this->uuid), 0, 8);
    }

    public function toArray(): array
    {
        return [
            'uuid'       => $this->uuid,
            'title'      => $this->title,
            'slug'       => $this->slug,
            'summary'    => $this->summary,
            'body'       => $this->body,
            'image_url'  => $this->imageUrl,
            'tags'       => $this->tags,
            'status'     => $this->status,
            'author'     => $this->authorToArray(),
            'created_at' => $this->createdAt,
            'updated_at' => $this->updatedAt,
        ];
    }

    private function authorToArray(): ?array
    {
        if ($this->author === null) {
            return null;
        }
        // The referenced user may have been deleted; a lazy proxy then throws
        // EntityNotFoundException on access. Treat a missing author as null.
        try {
            return [
                'uuid' => $this->author->getUuid(),
                'name' => $this->author->getRealName(),
            ];
        } catch (\Doctrine\ORM\EntityNotFoundException) {
            return null;
        }
    }

    public function toListArray(): array
    {
        return [
            'uuid'       => $this->uuid,
            'title'      => $this->title,
            'slug'       => $this->slug,
            'summary'    => $this->summary,
            'image_url'  => $this->imageUrl,
            'tags'       => $this->tags,
            'status'     => $this->status,
            'created_at' => $this->createdAt,
        ];
    }
}
