<?php

namespace App\Services;

use App\Models\Role;
use Illuminate\Database\Eloquent\Collection;
use App\Repositories\RoleRepository;
use Exception;

class RoleService
{
    protected $roleRepository;

    public function __construct(RoleRepository $roleRepository)
    {
        $this->roleRepository = $roleRepository;
    }

    public function getAllRoles(): Collection
    {
        return $this->roleRepository->getAll();
    }

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

    public function findByNama(string $nama): ?Role
    {
        return $this->roleRepository->findByNama($nama);
    }

    public function createRole(array $data): Role
    {
        $role = $this->roleRepository->findByNama($data['nama']);
        if ($role) {
            throw new \Exception("Duplikat nama");
        };

        return $this->roleRepository->create($data);
    }

    public function updateRole(int $id, array $data): ?Role
    {
        $role = $this->roleRepository->findById($id);
        if ($role->nama != $data['nama']) {
            $role_nama = $this->roleRepository->findByNama($data['nama']);
            if ($role_nama) {
                throw new \Exception("Duplikat nama");
            };
        }

        if (!$role) {
            throw new Exception("Role tidak ditemukan");
        }

        return $this->roleRepository->update($id, $data);
    }

    public function deleteRole(string $id): bool
    {
        $role = $this->roleRepository->findById($id);
        if (!$role) {
            throw new Exception('Role tidak ditemukan.');
        }

        return $this->roleRepository->delete($role);
    }
}
