package xml_loader

import (
	"encoding/xml"
	"fmt"
	"io"

	"gitea.urkob.com/urko/ess-etl-go/internal/request"
	"gitea.urkob.com/urko/ess-etl-go/pkg/domain"
)

type EmployeeWILoader struct {
	r request.RequestService
}

func NewEmployeeWILoader(r request.RequestService) EmployeeWILoader {
	return EmployeeWILoader{r: r}
}

func (e EmployeeWILoader) LoadEmployeeList(employeeIDList []string, from, to string) ([]domain.EmployeeWorkInformation, error) {
	reader, err := e.r.EmployeeWorkInformation(employeeIDList, from, to)
	if err != nil {
		return nil, fmt.Errorf("r.EmployeeWorkInformation: %s", err)
	}

	return loadFromXML(reader)
}

func (e EmployeeWILoader) LoadEmployee(employeeID, from, to string) ([]domain.EmployeeWorkInformation, error) {
	employeeIDList := []string{employeeID}

	reader, err := e.r.EmployeeWorkInformation(employeeIDList, from, to)
	if err != nil {
		return nil, fmt.Errorf("r.EmployeeWorkInformation: %s", err)
	}

	return loadFromXML(reader)
}

func loadFromXML(xmlFile io.Reader) ([]domain.EmployeeWorkInformation, error) {
	var awi domain.ArrayOfEmployeeWorkInformation

	if err := xml.NewDecoder(xmlFile).Decode(&awi); err != nil {
		return nil, fmt.Errorf("xml.NewDecoder.Decode: %s", err)
	}

	return awi.EmployeeWorkInfos, nil
}