package repository

import (
	"sort"
	"strconv"

	"gitlab.com/mbugroup/lti-api.git/internal/common/repository"
	entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
	utils "gitlab.com/mbugroup/lti-api.git/internal/utils"
	approvalutils "gitlab.com/mbugroup/lti-api.git/internal/utils/approvals"
	"gorm.io/gorm"
)

type ConstantRepository interface {
	GetConstants() map[string]interface{}
}

type ConstantRepositoryImpl struct {
	*repository.BaseRepositoryImpl[entity.Constant]
}

func NewConstantRepository(db *gorm.DB) ConstantRepository {
	return &ConstantRepositoryImpl{
		BaseRepositoryImpl: repository.NewBaseRepository[entity.Constant](db),
	}
}

func (r *ConstantRepositoryImpl) GetConstants() map[string]interface{} {
	flagList := make([]string, 0)
	for f := range utils.AllFlagTypes() {
		flagList = append(flagList, string(f))
	}
	sort.Strings(flagList)

	type approvalStepConstant struct {
		StepNumber uint16 `json:"step_number"`
		StepName   string `json:"step_name"`
	}

	workflowConstants := approvalutils.WorkflowConstants()
	workflowKeys := make([]string, 0, len(workflowConstants))
	for key := range workflowConstants {
		workflowKeys = append(workflowKeys, key)
	}
	sort.Strings(workflowKeys)

	approvalWorkflows := make([]map[string]interface{}, 0, len(workflowKeys))
	for _, key := range workflowKeys {
		stepMap := workflowConstants[key]
		if len(stepMap) == 0 {
			continue
		}

		stepList := make([]approvalStepConstant, 0, len(stepMap))
		for stepStr, label := range stepMap {
			stepNum, err := strconv.ParseUint(stepStr, 10, 16)
			if err != nil || stepNum == 0 {
				continue
			}
			stepList = append(stepList, approvalStepConstant{
				StepNumber: uint16(stepNum),
				StepName:   label,
			})
		}
		if len(stepList) == 0 {
			continue
		}
		sort.Slice(stepList, func(i, j int) bool {
			return stepList[i].StepNumber < stepList[j].StepNumber
		})

		approvalWorkflows = append(approvalWorkflows, map[string]interface{}{
			"key":   key,
			"steps": stepList,
		})
	}

	return map[string]interface{}{
		"flags": flagList,
		"warehouse_types": []string{
			"AREA",
			"LOKASI",
			"KANDANG",
		},
		"supplier_categories": []string{
			"BOP",
			"SAPRONAK",
		},
		"customer_supplier_types": []string{
			"BISNIS",
			"INDIVIDUAL",
		},
		"approval_workflows": approvalWorkflows,
	}
}
