package service

import (
	"backend-agenter/internal/models"
	"backend-agenter/internal/repository"
	"backend-agenter/internal/repository/agent"
	db "backend-agenter/internal/repository/database"
	"fmt"
	"strings"

	"go.uber.org/zap"
)

type quarantineFiles struct {
	av    db.Av
	agent agent.Agent
}

func newQuarantineService(repository *repository.Repository) Quarantine {
	return &quarantineFiles{
		av:    repository.AvRepository,
		agent: repository.AgentRepository,
	}
}

func (q *quarantineFiles) Get(cid int64) ([]string, error) {
	zap.S().Info("Service get quarantine starting the job...")

	avObject, agentPath, err := q.getAgentPath(cid)
	if err != nil {
		return nil, err
	}

	err = q.agent.StartSession(agentPath, avObject.Config)
	if err != nil {
		return nil, err
	}
	defer q.agent.StopSession()

	files, err := q.agent.GetQuarantineFiles(avObject.Config)
	if err != nil {
		return nil, err
	}

	return files, nil
}

func (q *quarantineFiles) IsQuarantine(cid int64) (bool, error) {
	avObject, agentPath, err := q.getAgentPath(cid)
	if err != nil {
		return false, err
	}

	err = q.agent.StartSession(agentPath, avObject.Config)
	if err != nil {
		return false, err
	}
	defer q.agent.StopSession()

	isFullScan, err := q.agent.IsFileInQuarantine(avObject.Config)
	if err != nil {
		return false, err
	}

	return isFullScan, nil
}

func (q *quarantineFiles) getAgentPath(cid int64) (*models.AvObject, string, error) {
	avObject, err := q.av.GetAvObject(cid)
	if err != nil {
		return nil, "", err
	}

	var url string

	urls, err := q.av.GetUrl(avObject.ObjectID)
	if err != nil {
		return nil, "", err
	}

	if (urls.Schema == "http" && urls.Port == uint16(80)) || (urls.Schema == "https" && urls.Port == uint16(443)) {
		url = fmt.Sprintf("%s://%s/%s", urls.Schema, urls.Host, strings.TrimLeft(urls.Path, "/"))
	} else {
		url = fmt.Sprintf("%s://%s:%d/%s", urls.Schema, urls.Host, urls.Port, strings.TrimLeft(urls.Path, "/"))
	}

	agentPath := fmt.Sprintf("%s%s", url, avObject.Config.AgentName)

	return avObject, agentPath, nil
}
