package dao

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

type TagDAO struct {
	db *sqlca.Engine
}

func NewTagDAO(db *sqlca.Engine) *TagDAO {
	return &TagDAO{
		db: db,
	}
}

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

// insert if not exist or update columns on duplicate key...
func (dao *TagDAO) Upsert(do *models.TagDO, columns ...string) (lastInsertId int64, err error) {
	return dao.db.Model(&do).Table(models.TableNameTag).Select(columns...).Upsert()
}

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

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

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

func (dao *TagDAO) QueryAll(pageNo, pageSize int, asc bool) (dos []*models.TagDO, total int64, err error) {
	e := dao.db.Model(&dos).
		Table(models.TableNameTag).
		Eq(models.TAG_COLUMN_IS_DELETED, 0).
		Page(pageNo, pageSize).
		Asc(models.TAG_COLUMN_CREATED_TIME)
	if asc {
		e.Asc(models.TAG_COLUMN_UPDATED_TIME, models.TAG_COLUMN_ID)
	} else {
		e.Desc(models.TAG_COLUMN_UPDATED_TIME, models.TAG_COLUMN_ID)
	}
	_, total, err = e.QueryEx()
	if err != nil {
		return nil, 0, log.Errorf(err.Error())
	}
	return
}
