package handler

import (
	"context"
	"crypto/tls"
	"solidarity-service/services"
	"git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
	gomail "gopkg.in/mail.v2"
)

func (h *SolidarityServiceHandler) PutFirebase(ctx context.Context, id string, token string, device_platform string) (err error) {
	err = h.Storage.CreateFirebaseToken(id, token, device_platform)
	return err
}

func (h *SolidarityServiceHandler) SendNotification(id, title, message string) (err error) {
	firebase_token, platfrom, _ := h.Storage.GetFirebaseToken(id)
	if err != nil {
		return err
	}
	if platfrom == "android" {
		_ = h.Services.Push.Send(
			services.Notification{
				Platform:   services.PushToAndroid,
				Recipients: []string{firebase_token},
				Title:      title,
				Message:    message,
			},
		)
	} else {
		_ = h.Services.Push.Send(
			services.Notification{
				Platform:   services.PushToIos,
				Recipients: []string{firebase_token},
				Title:      title,
				Message:    message,
			},
		)
	}

	return nil

}
func (h *SolidarityServiceHandler) SendEmail(id, title, message string) (err error) {
	resp, err := h.Services.MobilityAccounts.Client.GetAccount(context.Background(), &grpcapi.GetAccountRequest{Id: id})
	if err != nil {
		return err
	}

	account := h.Services.MobilityAccounts.ToAccountModel(resp.Account.ToStorageType())
	m := gomail.NewMessage()
	m.SetHeader("From", h.Config.GetString("emailing.smtp.username"))
	m.SetHeader("To", account.Email)
	m.SetHeader("Subject", title)
	m.SetBody("text/plain", message)
	d := gomail.NewDialer(h.Config.GetString("emailing.smtp.host"), h.Config.GetInt("emailing.smtp.port"), h.Config.GetString("emailing.smtp.username"),
		h.Config.GetString("emailing.smtp.password"))
	d.TLSConfig = &tls.Config{InsecureSkipVerify: true}
	if err := d.DialAndSend(m); err != nil {
		return err
	}
	return nil

}
