<?php

namespace App\Domain\Setting\Application\CommandHandler;

use App\Domain\Setting\Application\Command\UpsertContentSourceCommand;
use App\Domain\Setting\Domain\Contract\Repository\ContentSourceRepositoryInterface;
use App\Domain\Setting\Domain\Model\ContentSource;

readonly class UpsertContentSourceCommandHandler
{
    public function __construct(
        private ContentSourceRepositoryInterface $contentSourceRepository
    ) {
    }

    public function handle(UpsertContentSourceCommand $command): void
    {
        if ($command->id) {
            // Update existing
            $contentSource = $this->contentSourceRepository->findById($command->id);
            if ($contentSource) {
                $contentSource->update(
                    baseUrl: $command->baseUrl,
                    chapterUrlFormat: $command->chapterUrlFormat,
                    scrapingType: $command->scrapingType,
                    imageSelector: $command->imageSelector,
                    nextPageSelector: $command->nextPageSelector,
                    chapterSelector: $command->chapterSelector,
                    testSlug: $command->testSlug,
                    testChapterNumber: $command->testChapterNumber,
                );
                $this->contentSourceRepository->save($contentSource);
            }
        } else {
            // Create new
            $contentSource = ContentSource::create(
                baseUrl: $command->baseUrl,
                chapterUrlFormat: $command->chapterUrlFormat,
                scrapingType: $command->scrapingType,
                imageSelector: $command->imageSelector,
                nextPageSelector: $command->nextPageSelector,
                chapterSelector: $command->chapterSelector,
                testSlug: $command->testSlug,
                testChapterNumber: $command->testChapterNumber,
            );
            $this->contentSourceRepository->save($contentSource);
        }
    }
}
