<?php

declare(strict_types=1);

namespace ApiModel\Service;

use ApiModel\Domain\Repository\RoleRepositoryInterface;
use ApiModel\Domain\Repository\ProfileRepositoryInterface;
use ApiModel\Infrastructure\Persistence\Database;
use ApiModel\Shared\Exceptions\NotFoundException;

final class RoleService
{
    public function __construct(
        private readonly RoleRepositoryInterface $roles,
        private readonly ProfileRepositoryInterface $profiles
    ) {}

    public function listRoles(): array
    {
        return $this->roles->listAll();
    }

    public function getRole(string $id): array
    {
        $role = $this->roles->findById($id);
        if (!$role) {
            throw new NotFoundException('Rol no encontrado');
        }
        return $role;
    }

    public function createRole(string $nameEs, string $nameEn, ?string $descEs, ?string $descEn): array
    {
        $id = Database::uuid();
        $this->roles->insert($id, $nameEs, $nameEn, $descEs, $descEn);
        return $this->getRole($id);
    }

    public function updateRole(string $id, string $nameEs, string $nameEn, ?string $descEs, ?string $descEn, bool $isActive): array
    {
        $role = $this->roles->findById($id);
        if (!$role) {
            throw new NotFoundException('Rol no encontrado');
        }
        $this->roles->update($id, $nameEs, $nameEn, $descEs, $descEn, $isActive);
        return $this->getRole($id);
    }

    public function getPermissions(string $roleId): array
    {
        return $this->profiles->listByRole($roleId);
    }

    public function savePermission(string $roleId, string $pageId, bool $canView, bool $canCreate, bool $canEdit, bool $canDelete): void
    {
        $this->profiles->savePermission($roleId, $pageId, $canView, $canCreate, $canEdit, $canDelete);
    }

    public function deleteRole(string $id): void
    {
        $role = $this->roles->findById($id);
        if (!$role) {
            throw new NotFoundException('Rol no encontrado');
        }
        $this->roles->delete($id);
    }
}
