package controler

import (
	"context"
	"encoding/json"
	"fmt"
	"linhdevtran99/rest-api/models"
	"linhdevtran99/rest-api/rest-api/services"
	"linhdevtran99/rest-api/utils"
	"net/http"
	"sync"
	"time"
)

func RegisterNewAccount(w http.ResponseWriter, r *http.Request) error {
	if r.Method == http.MethodPost {
		var registerInfo models.CreateUser

		// get data from body
		_ = json.NewDecoder(r.Body).Decode(&registerInfo)

		//call function check info user type in
		_, responseAPI := services.CheckAndValidRegisterFiled(&registerInfo, w)
		//[fairy ok]

		if responseAPI != nil {
			return utils.WriteJSON(w, responseAPI.Code, responseAPI.Err)
		}

		//call function check data user use in past or not
		isError, responseAPI := services.CheckAccountValid(registerInfo.Username, registerInfo.Email)

		if isError == true {
			return utils.WriteJSON(w, responseAPI.Code, responseAPI.Err)
		}

		preUserData := &models.PreusersMongo{
			Username:        registerInfo.Username,
			Email:           registerInfo.Email,
			PhoneNumber:     registerInfo.PhoneNumber,
			HashPassword:    registerInfo.Password,
			UUID:            registerInfo.UUID,
			CreatedDate:     time.Now(),
			UpdateDate:      time.Now(),
			VerifySentCount: 1,
		}

		ctx, cancel := context.WithCancel(context.Background())
		defer cancel()

		var wg sync.WaitGroup

		//otpChannel := make(chan models.OtpGenerate, 1)
		//mailChannel := make(chan models.MailVefiry, 1)
		done := make(chan struct{})

		var pipelineError error

		wg.Add(1)
		counter, timerCreate := services.CheckAndWritePreuser(preUserData, &wg, cancel, pipelineError)
		fmt.Println("counter", counter)
		fmt.Println("timerCreate", timerCreate)
		time.Sleep(20 * time.Second)
		cancel()
		//wg.Add(1)
		//go utils.GenOTP(preUserData, counter, 6, w, otpChannel, pipelineError, cancel, &wg)
		//wg.Add(1)
		////go utils.EncryptAESMailLink(preUserData, w, mailChannel, &wg, timerCreate)
		////wg.Add(1)
		////go services.CreateMailVerify(preUserData, otpChannel, mailChannel, w, errChan)
		////go services.WriteOTPInRedis(counter, preUserData, otpChannel, w)
		////wg.Done()
		////err := <-errChan
		////close(errChan)
		////if err != nil {
		////	fmt.Println("Internal Log: Fail to send email check smtp")
		////	return err
		////}
		////if err == nil {
		////	_ = utils.WriteJSON(w, http.StatusOK, models.SuccessAPI{
		////		Message: "Success register account please verify your account",
		////	})
		////}
		////
		wg.Wait()
		////create dummy error
		//err = fmt.Errorf("dummy error")
		select {
		case <-done:
			// Error occurred, wait for all goroutines to finish
			wg.Wait()
		case <-ctx.Done():
			// Context cancelled, wait for all goroutines to finish
			wg.Wait()
		}
		return nil

	}
	return nil
}
