package dao

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

type WkSpiderQnaDAO struct {
	db *sqlca.Engine
}

func NewWkSpiderQnaDAO(db *sqlca.Engine) *WkSpiderQnaDAO {
	return &WkSpiderQnaDAO{
		db: db,
	}
}

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

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

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

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

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

func (dao *WkSpiderQnaDAO) QueryLatest(lastId int64) (dos []*models.WkSpiderQnaDO, err error) {
	_, err = dao.db.Model(&dos).
		Table(models.TableNameWkSpiderQna).
		Gt(models.WK_SPIDER_NEWS_COLUMN_ID, lastId).
		Asc(models.WK_SPIDER_QNA_COLUMN_ID).
		Limit(1000).
		Query()
	if err != nil {
		return nil, log.Errorf(err.Error())
	}
	return dos, nil
}
