<?php

namespace App\Modules\Admin\Tenancy\Services;

use App\Modules\Admin\Tenancy\DTOs\ModuleData;
use App\Modules\Admin\Tenancy\Models\Module;
use App\Modules\Admin\Tenancy\Repositories\ModuleRepository;
use Illuminate\Database\Eloquent\Collection;
use RuntimeException;

class ModuleService
{
    public function __construct(
        private readonly ModuleRepository $repository,
        private readonly ModuleRegistryService $registry,
    ) {}

    public function list(): Collection
    {
        return $this->repository->all();
    }

    public function create(ModuleData $data): Module
    {
        $module = $this->repository->create($data->toArray());
        $this->registry->forget();

        return $module;
    }

    public function update(Module $module, ModuleData $data): Module
    {
        $updated = $this->repository->update($module, $data->toArray());
        $this->registry->forget();

        return $updated;
    }

    public function delete(Module $module): void
    {
        if ($module->plans()->exists()) {
            throw new RuntimeException('Cannot delete a module that is assigned to one or more plans.');
        }

        $this->repository->delete($module);
        $this->registry->forget();
    }
}
