package messaging

import (
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/ses"
	"github.com/jinzhu/gorm"
	"gitlab.com/pactual1/backend/config"
	"gitlab.com/pactual1/backend/models"
)

type service struct {
	ch  chan models.Notification
	db  *gorm.DB
	ech chan models.EmailNotification
	ses *ses.SES
}

var MessagingChannel chan models.Notification
var EmailChannel chan models.EmailNotification

func NewService(ch chan models.Notification, ech chan models.EmailNotification, db *gorm.DB) service {
	MessagingChannel = ch
	EmailChannel = ech
	log.Printf("Aws %v , %v", config.AppConfig.AWS.AccessKey, config.AppConfig.AWS.SecretKey)
	// Create a new session in the us-west-2 region.
	sess, err := session.NewSession(&aws.Config{
		Region:      aws.String("us-east-1"),
		Credentials: credentials.NewStaticCredentials(config.AppConfig.AWS.AccessKey, config.AppConfig.AWS.SecretKey, "")},
	)
	if err != nil {
		fmt.Printf("Error creating AWS session: %v\n", err)
		return service{}
	}
	// Create an SES session.
	svc := ses.New(sess)
	return service{
		ch:  MessagingChannel,
		ech: EmailChannel,
		ses: svc,
	}

}

func (s service) MessagingService() {
	for notification := range s.ch {
		fmt.Println("Messaging Service received: ", notification)

		// Save the notification to the database
		if err := s.db.Create(&notification).Error; err != nil {
			fmt.Printf("Error saving notification to DB: %v\n", err)
		}
	}

}

func (s service) SendEmailService() {
	for emailNotification := range s.ech {
		fmt.Println("Email Service received: ", emailNotification)

		// Send email via SES
		input := &ses.SendEmailInput{
			Destination: &ses.Destination{
				ToAddresses: []*string{
					aws.String(emailNotification.Email),
				},
			},
			Message: &ses.Message{
				Body: &ses.Body{
					Text: &ses.Content{
						Data: aws.String(emailNotification.Body),
					},
				},
				Subject: &ses.Content{
					Data: aws.String(emailNotification.Subject),
				},
			},
			Source: aws.String("app@pactualdev.com"), // Replace with your SES verified email address
		}
		_, err := s.ses.SendEmail(input)
		if err != nil {
			fmt.Printf("Error sending email: %v\n", err)
		} else {
			fmt.Println("Email sent successfully")
		}
	}
}

func GetMessagingChannel() chan models.Notification {
	return MessagingChannel
}

func GetEmailChannel() chan models.EmailNotification {
	return EmailChannel
}
