<?php

namespace App\Domain\Shared\Infrastructure\Persistence\Mapper;

use App\Domain\Scraping\Domain\Model\ScrapingJob;
use App\Domain\Shared\Domain\Model\Job;
use App\Domain\Shared\Domain\Model\JobStatus;
use App\Domain\Shared\Infrastructure\Persistence\Entity\JobEntity;

readonly class JobMapper
{
    public function toEntity(Job $job): JobEntity
    {
        $entity = new JobEntity();
        $entity->setId($job->id)
            ->setType($job->type)
            ->setStatus($job->status->value)
            ->setCreatedAt($job->createdAt)
            ->setStartedAt($job->startedAt)
            ->setCompletedAt($job->completedAt)
            ->setFailureReason($job->failureReason)
            ->setAttempts($job->attempts)
            ->setMaxAttempts($job->maxAttempts)
            ->setContext($job->context);

        return $entity;
    }

    public function toDomain(JobEntity $entity): Job
    {
        $job = match($entity->getType()) {
            'scraping_job' => new ScrapingJob(
                $entity->getId(),
                $entity->getContext()['mangaId'],
                $entity->getContext()['chapterNumber'],
                $entity->getContext()['sourceId']
            ),
            default => throw new \RuntimeException(sprintf('Unknown job type: %s', $entity->getType()))
        };

        $job->status = JobStatus::from($entity->getStatus());
        $job->createdAt = $entity->getCreatedAt();
        $job->startedAt = $entity->getStartedAt();
        $job->completedAt = $entity->getCompletedAt();
        $job->failureReason = $entity->getFailureReason();
        $job->attempts = $entity->getAttempts();
        $job->maxAttempts = $entity->getMaxAttempts();
        $job->context = $entity->getContext();

        return $job;
    }
}
