package tasks

import (
	"context"
	"encoding/json"
	"net/http"

	"repository.basistech.ru/BASIS/dynamix-golang-sdk/v14/internal/validators"
)

// ListRequest struct to get list of audits
type ListRequest struct {
	// Find by guId
	// Required: false
	TaskID string `url:"taskId,omitempty" json:"taskId,omitempty"`

	// Find by auditId
	// Required: false
	AuditID string `url:"auditId,omitempty" json:"auditId,omitempty"`

	// Find by status
	// Required: false
	Status string `url:"status,omitempty" json:"status,omitempty"`

	// Find by completed True or False
	// Required: false
	Completed interface{} `url:"completed,omitempty" json:"completed,omitempty" validate:"omitempty,isBool"`

	// Sort by one of supported fields, format +|-(field)
	// Required: false
	SortBy string `url:"sortBy,omitempty" json:"sortBy,omitempty" validate:"omitempty,sortBy"`

	// Find all tasks after point in time (unixtime)
	// Required: false
	UpdateTimeAt uint64 `url:"updateTimeAt,omitempty" json:"updateTimeAt,omitempty"`

	// Find all tasks before point in time (unixtime)
	// Required: false
	UpdateTimeTo uint64 `url:"updateTimeTo,omitempty" json:"updateTimeTo,omitempty"`

	// Page number
	// Default: 0
	// Default: 0
	// Required: false
	Page uint64 `url:"page,omitempty" json:"page,omitempty"`

	// Page size
	// Default: 0
	// Default: 0
	// Required: false
	Size uint64 `url:"size,omitempty" json:"size,omitempty"`
}

// List gets list of user API task with status PROCESSING as a ListTasks struct
func (t Tasks) List(ctx context.Context, req ListRequest) (*ListTasks, error) {

	res, err := t.ListRaw(ctx, req)
	if err != nil {
		return nil, err
	}

	item := ListTasks{}

	err = json.Unmarshal(res, &item)
	if err != nil {
		return nil, err
	}

	return &item, nil
}

// ListRaw gets list of user API task with status PROCESSING as an array of bytes
func (t Tasks) ListRaw(ctx context.Context, req ListRequest) ([]byte, error) {

	err := validators.ValidateRequest(req)
	if err != nil {
		return nil, validators.ValidationErrors(validators.GetErrors(err))
	}

	url := "/cloudbroker/tasks/list"

	res, err := t.client.DecortApiCall(ctx, http.MethodPost, url, req)
	return res, err
}
