package validator

import (
	"apskel-pos-be/internal/models"
	"fmt"
	"strings"

	"github.com/go-playground/validator/v10"
)

type ChartOfAccountTypeValidator interface {
	ValidateCreateChartOfAccountType(req *models.CreateChartOfAccountTypeRequest) error
	ValidateUpdateChartOfAccountType(req *models.UpdateChartOfAccountTypeRequest) error
}

type ChartOfAccountTypeValidatorImpl struct {
	validator *validator.Validate
}

func NewChartOfAccountTypeValidator() ChartOfAccountTypeValidator {
	return &ChartOfAccountTypeValidatorImpl{
		validator: validator.New(),
	}
}

func (v *ChartOfAccountTypeValidatorImpl) ValidateCreateChartOfAccountType(req *models.CreateChartOfAccountTypeRequest) error {
	if err := v.validator.Struct(req); err != nil {
		return err
	}

	// Additional custom validations
	if strings.TrimSpace(req.Name) == "" {
		return fmt.Errorf("name cannot be empty")
	}

	if strings.TrimSpace(req.Code) == "" {
		return fmt.Errorf("code cannot be empty")
	}

	// Validate code format (alphanumeric, uppercase)
	if !isValidCodeFormat(req.Code) {
		return fmt.Errorf("code must be alphanumeric and uppercase")
	}

	return nil
}

func (v *ChartOfAccountTypeValidatorImpl) ValidateUpdateChartOfAccountType(req *models.UpdateChartOfAccountTypeRequest) error {
	if err := v.validator.Struct(req); err != nil {
		return err
	}

	// Additional custom validations
	if req.Name != nil && strings.TrimSpace(*req.Name) == "" {
		return fmt.Errorf("name cannot be empty")
	}

	if req.Code != nil && strings.TrimSpace(*req.Code) == "" {
		return fmt.Errorf("code cannot be empty")
	}

	// Validate code format if provided
	if req.Code != nil && !isValidCodeFormat(*req.Code) {
		return fmt.Errorf("code must be alphanumeric and uppercase")
	}

	return nil
}

func isValidCodeFormat(code string) bool {
	// Check if code is alphanumeric and uppercase
	for _, char := range code {
		if !((char >= 'A' && char <= 'Z') || (char >= '0' && char <= '9')) {
			return false
		}
	}
	return true
}
