package dao

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

type WkAigQnaDAO struct {
	db *sqlca.Engine
}

func NewWkAigQnaDAO(db *sqlca.Engine) *WkAigQnaDAO {
	return &WkAigQnaDAO{
		db: db,
	}
}

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

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

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

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

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

func (dao *WkAigQnaDAO) QueryLatest(strTable string, lastId int64) (dos []*models.WkAigQnaDO, err error) {
	_, err = dao.db.Model(&dos).
		Table(strTable).
		Gt(models.WK_AIG_NEWS_COLUMN_ID, lastId).
		Asc(models.WK_AIG_NEWS_COLUMN_ID).
		Limit(1000).
		Query()
	if err != nil {
		return nil, log.Errorf(err.Error())
	}
	return dos, nil
}
