package agent

import (
	"backend-agenter/internal/config"
	"backend-agenter/internal/models"
	"time"

	rqst "gitlab.wtotem.net/webtotem/backend-agent-requestor"
	"go.uber.org/zap"
)

type AgentRepository struct {
	session rqst.AgentSession
	config  *config.Agent
	timeout time.Duration
}

func New(config *config.Agent) *AgentRepository {
	return &AgentRepository{
		config:  config,
		timeout: config.Timeout,
	}
}

func (a *AgentRepository) StartSession(agentUrl string, config *models.Config) error {
	opts := make([]rqst.SessionOption, 0, 5)
	opts = append(opts, rqst.GetSessionTimeoutOption(a.timeout))
	if config.Proxy != "" {
		opts = append(opts, rqst.GetSessionProxyOption(config.Proxy))
	}

	a.session = rqst.NewAgentSession(agentUrl, config.PrivateKey, config.UserID, config.AgentKey, opts...)
	err := a.session.Start()
	if err != nil {
		zap.S().Errorf("Error while starting session with agent: %s.", err.Error())
		return models.ErrStartSession
	}

	zap.S().Infof("Successfully started new session")

	return nil
}

func (a *AgentRepository) StopSession() {
	a.session.Stop()
}

func (a *AgentRepository) GetQuarantineFiles(config *models.Config) ([]string, error) {
	zap.S().Info("Sending get quarantine cmd to agent")

	cmd := &rqst.Command{
		Module: a.config.ModuleName,
		Key:    config.AvDecryptKey,
		Method: "chacha20",
		CMD:    models.CmdGetQuarantine,
		Params: map[string]bool{
			"full_scan": a.config.FullScan,
		},
	}

	var response models.AgentQuarantineFilesResponse
	err := a.session.SendRequest(cmd, &response)
	if err != nil {
		zap.S().Errorf("Error while sending request with %s command: %s", cmd.CMD, err.Error())
		return nil, models.ErrFromAgent
	}

	zap.S().Infof("Successfully got response from agent: %v", response)

	return response.Files, nil
}

func (a *AgentRepository) IsFileInQuarantine(config *models.Config) (bool, error) {
	cmd := &rqst.Command{
		Module: a.config.ModuleName,
		Key:    config.AvDecryptKey,
		Method: "chacha20",
		CMD:    models.CmdGetQuarantine,
		Params: map[string]bool{
			"is_quarantine": a.config.IsQuarantine,
		},
	}

	var response models.AgentIsQuarantineResponse
	err := a.session.SendRequest(cmd, &response)
	if err != nil {
		zap.S().Errorf("Error while sending request with %s command: %s", cmd.CMD, err.Error())
		return false, models.ErrFromAgent
	}

	return response.IsQuarantine, nil
}
