package dao

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

type WkAigNewsDAO struct {
	db *sqlca.Engine
}

func NewWkAigNewsDAO(db *sqlca.Engine) *WkAigNewsDAO {
	return &WkAigNewsDAO{
		db: db,
	}
}

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

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

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

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

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

func (dao *WkAigNewsDAO) QueryLatest(strTable string, lastId int64) (dos []*models.WkAigNewsDO, 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
}
