package dao

import (
	"fmt"
	"github.com/civet148/sqlca/v2"
	"intent-system/pkg/dal/models"
)

type EmailTemplateDAO struct {
	db *sqlca.Engine
}

func NewEmailTemplateDAO(db *sqlca.Engine) *EmailTemplateDAO {
	return &EmailTemplateDAO{
		db: db,
	}
}

// insert into table by data model
func (dao *EmailTemplateDAO) Insert(do *models.TemplateDO) (lastInsertId int64, err error) {
	return dao.db.Model(&do).Table(models.TableNameTemplate).Insert()
}

// insert if not exist or update columns on duplicate key...
func (dao *EmailTemplateDAO) Upsert(do *models.TemplateDO, columns ...string) (lastInsertId int64, err error) {
	if len(columns) == 0 {
		return 0, fmt.Errorf("no columns to update")
	}
	return dao.db.Model(&do).Table(models.TableNameTemplate).Select(columns...).Upsert()
}

// update table set columns where id=xxx
func (dao *EmailTemplateDAO) Update(do *models.TemplateDO, columns ...string) (rows int64, err error) {
	if len(columns) == 0 {
		return 0, fmt.Errorf("no columns to update")
	}
	return dao.db.Model(&do).Table(models.TableNameTemplate).Select(columns...).Update()
}

// query records by id
func (dao *EmailTemplateDAO) QueryById(id interface{}, columns ...string) (do *models.TemplateDO, err error) {
	if _, err = dao.db.Model(&do).Table(models.TableNameTemplate).Id(id).Select(columns...).Query(); err != nil {
		return nil, err
	}
	return
}

// query records by conditions
func (dao *EmailTemplateDAO) QueryByCondition(conditions map[string]interface{}, columns ...string) (dos []*models.TemplateDO, err error) {
	if len(conditions) == 0 {
		return nil, fmt.Errorf("condition must not be empty")
	}
	e := dao.db.Model(&dos).Table(models.TableNameTemplate).Select(columns...)
	for k, v := range conditions {
		e.Eq(k, v)
	}
	if _, err = e.Query(); err != nil {
		return nil, err
	}
	return
}

func (dao *EmailTemplateDAO) QueryByTypeLang(templateType models.TemplateType, lang string, columns ...string) (do *models.TemplateDO, err error) {
	e := dao.db.Model(&do).
		Table(models.TableNameTemplate).
		Select(columns...).
		Eq(models.TEMPLATE_COLUMN_TEMPLATE_TYPE, templateType).
		Eq(models.TEMPLATE_COLUMN_LANGUAGE, lang)
	if _, err = e.Query(); err != nil {
		return nil, err
	}
	return
}
