package dao

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

type WkSpiderNewsDAO struct {
	db *sqlca.Engine
}

func NewWkSpiderNewsDAO(db *sqlca.Engine) *WkSpiderNewsDAO {
	return &WkSpiderNewsDAO{
		db: db,
	}
}

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

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

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

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

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

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