package models

import (
	"github.com/sujit-baniya/fiber-boilerplate/app"
	"gorm.io/gorm"
)

type SmtpConfig struct {
	gorm.Model
	Host        string `json:"host" gorm:"column:host"`
	Port        int    `json:"port" gorm:"column:port;default:587"`
	Username    string `json:"username" gorm:"column:username"`
	Password    string `json:"password" gorm:"column:password"` // cifrado AES
	Encryption  string `json:"encryption" gorm:"column:encryption;default:'tls'"`
	FromAddress string `json:"from_address" gorm:"column:from_address"`
	FromName    string `json:"from_name" gorm:"column:from_name"`
	Activo      bool   `json:"activo" gorm:"column:activo;default:true"`
}

func (SmtpConfig) TableName() string { return "smtp_config" }

func GetSmtpConfig() (*SmtpConfig, error) {
	var item SmtpConfig
	if err := app.Http.Database.DB.Where("activo = ?", true).First(&item).Error; err != nil {
		return nil, err
	}
	return &item, nil
}

func SaveSmtpConfig(s SmtpConfig) error {
	// Desactivar config previa
	app.Http.Database.DB.Model(&SmtpConfig{}).Where("activo = ?", true).
		Update("activo", false)
	s.Activo = true
	if s.ID > 0 {
		return app.Http.Database.DB.Model(&s).Updates(map[string]interface{}{
			"host":         s.Host,
			"port":         s.Port,
			"username":     s.Username,
			"password":     s.Password,
			"encryption":   s.Encryption,
			"from_address": s.FromAddress,
			"from_name":    s.FromName,
			"activo":       true,
		}).Error
	}
	return app.Http.Database.DB.Create(&s).Error
}
