<?php

namespace App\Domain\Setting\Domain\Model;

final class ContentSource
{
    public function __construct(
        private ?int $id,
        private string $baseUrl,
        private string $chapterUrlFormat,
        private string $scrapingType,
        private ?string $imageSelector = null,
        private ?string $nextPageSelector = null,
        private ?string $chapterSelector = null,
    ) {
    }

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

    public function getBaseUrl(): string
    {
        return $this->baseUrl;
    }

    public function getChapterUrlFormat(): string
    {
        return $this->chapterUrlFormat;
    }

    public function getScrapingType(): string
    {
        return $this->scrapingType;
    }

    public function getImageSelector(): ?string
    {
        return $this->imageSelector;
    }

    public function getNextPageSelector(): ?string
    {
        return $this->nextPageSelector;
    }

    public function getChapterSelector(): ?string
    {
        return $this->chapterSelector;
    }

    public function updateId(int $id): void
    {
        $this->id = $id;
    }

    public function getCleanBaseUrl(): string
    {
        return preg_replace(
            '/^(https?:\/\/)?(www\.)?|\/+$/',
            '',
            $this->baseUrl
        );
    }

    public static function create(
        string $baseUrl,
        string $chapterUrlFormat,
        string $scrapingType,
        ?string $imageSelector = null,
        ?string $nextPageSelector = null,
        ?string $chapterSelector = null,
    ): self {
        return new self(
            id: null,
            baseUrl: $baseUrl,
            chapterUrlFormat: $chapterUrlFormat,
            scrapingType: $scrapingType,
            imageSelector: $imageSelector,
            nextPageSelector: $nextPageSelector,
            chapterSelector: $chapterSelector,
        );
    }

    public function update(
        string $baseUrl,
        string $chapterUrlFormat,
        string $scrapingType,
        ?string $imageSelector = null,
        ?string $nextPageSelector = null,
        ?string $chapterSelector = null,
    ): void {
        $this->baseUrl = $baseUrl;
        $this->chapterUrlFormat = $chapterUrlFormat;
        $this->scrapingType = $scrapingType;
        $this->imageSelector = $imageSelector;
        $this->nextPageSelector = $nextPageSelector;
        $this->chapterSelector = $chapterSelector;
    }
}
