package mappers

import (
	permissionV1 "service/internal/infrastructure/transport/grpc/gen/permission/v1"
	"service/internal/master/role/permission"
)

// mapAccessTreeToProto secara rekursif mengubah tree dari service ke format proto.
func mapAccessTreeToProto(serviceAccess []*permission.AccessTreeItem) []*permissionV1.AccessTreeItem {
	if serviceAccess == nil {
		return nil
	}

	protoAccess := make([]*permissionV1.AccessTreeItem, len(serviceAccess))
	for i, item := range serviceAccess {
		protoItem := &permissionV1.AccessTreeItem{
			Id:       item.ID,
			Name:     item.Name,
			Icon:     item.Icon,
			Url:      item.URL,
			Level:    int32(item.Level),
			Sort:     int32(item.Sort),
			Active:   item.Active,
			Children: mapAccessTreeToProto(item.Children), // Panggilan rekursif
		}

		if item.Permission != nil {
			protoItem.Permission = &permissionV1.Permission{
				Create:  item.Permission.Create,
				Read:    item.Permission.Read,
				Update:  item.Permission.Update,
				Delete:  item.Permission.Delete,
				Disable: item.Permission.Disable,
			}
		}
		protoAccess[i] = protoItem
	}
	return protoAccess
}

// MapRolePermissionTreeToProto adalah fungsi utama untuk mengubah seluruh respons tree.
func MapRolePermissionTreeToProto(serviceResponse *permission.RolePermissionTreeResponse) *permissionV1.RolePermissionTreeResponse {
	if serviceResponse == nil {
		return nil
	}

	return &permissionV1.RolePermissionTreeResponse{
		Success: serviceResponse.Success,
		Data: &permissionV1.RolePermissionData{
			Role: serviceResponse.Data.Role,
			// Group:  serviceResponse.Data.Group,
			Access: mapAccessTreeToProto(serviceResponse.Data.Access),
		},
	}
}
