package adminrole

import (
	"context"
	"errors"
)

var ErrDependencyUnavailable = errors.New("dependency unavailable")

type Service struct {
	repo *Repository
}

func NewService(repo *Repository) *Service {
	return &Service{repo: repo}
}

func (s *Service) List(ctx context.Context) ([]RoleDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	return s.repo.List(ctx)
}

func (s *Service) FindByID(ctx context.Context, id uint64) (*RoleDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	return s.repo.FindByID(ctx, id)
}

func (s *Service) Create(ctx context.Context, req CreateRoleRequest) (*RoleDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	if req.Code == "" || req.Name == "" {
		return nil, errors.New("code and name are required")
	}
	return s.repo.Create(ctx, req)
}

func (s *Service) Update(ctx context.Context, id uint64, req UpdateRoleRequest) (*RoleDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	return s.repo.Update(ctx, id, req)
}

func (s *Service) Delete(ctx context.Context, id uint64) error {
	if s.repo == nil {
		return ErrDependencyUnavailable
	}
	return s.repo.Delete(ctx, id)
}

func (s *Service) AssignPermissions(ctx context.Context, roleID uint64, req AssignPermissionsRequest) error {
	if s.repo == nil {
		return ErrDependencyUnavailable
	}
	return s.repo.AssignPermissions(ctx, roleID, req.PermissionIDs)
}

func (s *Service) ListPermissions(ctx context.Context) ([]PermissionDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	return s.repo.ListPermissions(ctx)
}
