package utils

import (
	"encoding/json"
	"fmt"
	"go-account-register/config"
	"strings"

	"github.com/PuerkitoBio/goquery"
	"github.com/go-resty/resty/v2"
)

type Firstmail struct {
}

type MailResponse struct {
	Message string `json:"message"`
}

func (f *Firstmail) GetFirstmailMail(username, password string) (*MailResponse, error) {
	client := resty.New()
	appConfig, _ := config.LoadConfig()
	url := fmt.Sprintf("%s?username=%s&password=%s",
		appConfig.Firstmail.ApiUrl, username, password)

	resp, err := client.R().
		SetHeader("accept", "application/json").
		SetHeader("X-API-KEY", appConfig.Firstmail.ApiToken).
		Get(url)

	if err != nil {
		return nil, err
	}

	var data MailResponse
	if err := json.Unmarshal(resp.Body(), &data); err != nil {
		return nil, err
	}

	return &data, nil
}

func (f *Firstmail) GetMailCode(username, password string) string {
	res, err := f.GetFirstmailMail(username, password)
	if err != nil {
		return "0"
	}

	htmlStr := res.Message
	fmt.Println(htmlStr)

	doc, err := goquery.NewDocumentFromReader(strings.NewReader(htmlStr))
	if err != nil {
		return "0"
	}

	code := ""
	doc.Find("td.h1.black").Each(func(i int, s *goquery.Selection) {
		if code == "" {
			code = strings.TrimSpace(s.Text())
		}
	})

	if code == "" {
		return "0"
	}
	return code
}
