package regras

import (
	"fmt"
	"regexp"
	"strconv"
	"strings"
)

func SoNumero(str string) string {
	if str == "" {
		return "0"
	}
	var b strings.Builder
	for _, r := range str {
		if r >= '0' && r <= '9' {
			b.WriteRune(r)
		} else if r == ' ' {
			b.WriteRune(r)
		}
	}
	out := strings.TrimSpace(b.String())
	if out == "" {
		return "0"
	}
	return out
}

func TratarAreaVivareal(area, tipoImovel string) string {
	_ = tipoImovel
	nova := regexp.MustCompile(`[A-Za-z]`).ReplaceAllString(area, "")
	nova = strings.ReplaceAll(nova, "²", "")
	parts := strings.Split(nova, ",")
	if len(parts) > 0 {
		nova = strings.ReplaceAll(parts[0], ".", "")
	}
	nova = strings.TrimSpace(nova)
	if nova == "" {
		return "50"
	}
	return nova
}

var tiposSemBanheiro = map[string]struct{}{
	"Residential / Land Lot":           {},
	"Commercial / Industrial":            {},
	"Commercial / Building":            {},
	"Commercial / Land Lot":              {},
	"Commercial / Business":              {},
	"Commercial / Studio":                {},
	"Commercial / Edificio Comercial":    {},
}

func TratarBanheiroVivareal(banheiro, tipoImovel string) string {
	if _, ok := tiposSemBanheiro[tipoImovel]; ok {
		return ""
	}
	b := strings.TrimSpace(banheiro)
	if b == "" || b == "0" {
		return "<Bathrooms>1</Bathrooms>"
	}
	return fmt.Sprintf("<Bathrooms>%s</Bathrooms>", b)
}

func TratarBanheiroChavesNaMao(banheiro, tipoImovel string) string {
	if _, ok := tiposSemBanheiro[tipoImovel]; ok {
		return ""
	}
	b := strings.TrimSpace(banheiro)
	if b == "" || b == "0" {
		return "<Bathrooms>0</Bathrooms>"
	}
	return fmt.Sprintf("<Bathrooms>%s</Bathrooms>", b)
}

func TratarQuartoVivareal(quarto, tipoImovel string) string {
	if _, ok := tiposSemBanheiro[tipoImovel]; ok {
		return "<Bedrooms>0</Bedrooms>"
	}
	q := SoNumero(quarto)
	if q == "" || q == "0" {
		return "<Bedrooms>0</Bedrooms>"
	}
	return fmt.Sprintf("<Bedrooms>%s</Bedrooms>", q)
}

func TratarQuartoChavesNaMao(quarto, tipoImovel string) string {
	return TratarQuartoVivareal(quarto, tipoImovel)
}

func TratarQuartoZap(quarto, tipoImovel, refCaixa string, idMaster int) string {
	if idMaster == 4523 && refCaixa != "" {
		return "<QtdDormitorios>1</QtdDormitorios>"
	}
	if _, ok := tiposSemBanheiro[tipoImovel]; ok {
		return "<QtdDormitorios>1</QtdDormitorios>"
	}
	q := SoNumero(quarto)
	if q == "" || q == "0" {
		return "<QtdDormitorios>0</QtdDormitorios>"
	}
	return fmt.Sprintf("<QtdDormitorios>%s</QtdDormitorios>", q)
}

func BanheiroMercadoLivre(valor string) string {
	v, _ := strconv.Atoi(SoNumero(valor))
	if v > 0 {
		return fmt.Sprintf("<QtdBanheiros>%d</QtdBanheiros>", v)
	}
	return ""
}

func TrataCampoVazio(valor string) string {
	if strings.TrimSpace(valor) == "" {
		return "0"
	}
	return valor
}
