package dao

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

type SubscriberDAO struct {
	db *sqlca.Engine
}

func NewSubscriberDAO(db *sqlca.Engine) *SubscriberDAO {
	return &SubscriberDAO{
		db: db,
	}
}

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

// insert if not exist or update columns on duplicate key...
func (dao *SubscriberDAO) Upsert(do *models.SubscriberDO, columns ...string) (lastInsertId int64, err error) {
	_, err = dao.db.Model(&do).
		Table(models.TableNameSubscriber).
		Select(models.SUBSCRIBER_COLUMN_ID).
		Eq(models.SUBSCRIBER_COLUMN_EMAIL, do.Email).
		Query()
	if err != nil {
		return 0, log.Error(err.Error())
	}
	if do.Id != 0 {
		return dao.db.Model(&do).Table(models.TableNameSubscriber).Select(columns...).Update()
	}
	return dao.db.Model(&do).Table(models.TableNameSubscriber).Select(columns...).Insert()
}

// update table set columns where id=xxx
func (dao *SubscriberDAO) Update(do *models.SubscriberDO, columns ...string) (rows int64, err error) {
	return dao.db.Model(&do).Table(models.TableNameSubscriber).Select(columns...).Update()
}

func (dao *SubscriberDAO) DeleteByUserEmail(do *models.SubscriberDO, columns ...string) (rows int64, err error) {
	return dao.db.Model(&do).
		Table(models.TableNameSubscriber).
		Eq(models.SUBSCRIBER_COLUMN_EMAIL, do.Email).
		Select(columns...).
		Update()
}

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

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

func (dao *SubscriberDAO) QueryByEmail(strEmail string) (do *models.SubscriberDO, err error) {
	_, err = dao.db.Model(&do).
		Table(models.TableNameSubscriber).
		Eq(models.SUBSCRIBER_COLUMN_EMAIL, strEmail).
		Eq(models.SUBSCRIBER_COLUMN_IS_DELETED, 0).
		Query()
	if err != nil {
		return nil, log.Error(err.Error())
	}
	return do, nil
}
