<?php

namespace App\Services;

use App\Models\Profession;
use App\Repositories\Eloquent\ProfessionManagementRepository;
use Illuminate\Validation\ValidationException;

class ProfessionManagementService
{
    public function __construct(private ProfessionManagementRepository $repository) {}

    public function index(array $filters = []): array
    {
        return [
            'professions' => $this->repository->paginate($filters),
            'parents' => $this->repository->parents(),
            'stats' => $this->repository->stats(),
        ];
    }

    public function save(?Profession $profession, array $data): Profession
    {
        $parentId = (int) $data['parent_id'];
        if ($profession && $parentId === $profession->id) {
            throw ValidationException::withMessages(['parent_id' => 'A profession cannot be its own parent.']);
        }
        if ($profession && $parentId > 0 && $profession->children()->exists()) {
            throw ValidationException::withMessages(['parent_id' => 'A profession with sub-professions cannot be converted into a sub-profession.']);
        }
        if ($parentId > 0 && ! $this->repository->parentExists($parentId)) {
            throw ValidationException::withMessages(['parent_id' => 'Select a valid parent profession.']);
        }

        return $profession ? $this->repository->update($profession, $data) : $this->repository->create($data);
    }
}
