package dao

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

type NewsSpiderDAO struct {
	db *sqlca.Engine
}

func NewNewsSpiderDAO(db *sqlca.Engine) *NewsSpiderDAO {
	return &NewsSpiderDAO{
		db: db,
	}
}

// insert into table by data model
func (dao *NewsSpiderDAO) Insert(do *models.NewsSpiderDO) (lastInsertId int64, err error) {
	_, err = dao.db.Model(&do).
		Table(models.TableNameNewsSpider).
		Select(models.NEWS_SPIDER_COLUMN_ID).
		Eq(models.NEWS_SPIDER_COLUMN_ORG_ID, do.OrgId).
		Query()
	if err != nil {
		return 0, log.Errorf(err.Error())
	}
	if do.Id != 0 {
		return do.Id, nil
	}
	return dao.db.Model(&do).Table(models.TableNameNewsSpider).Insert()
}

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

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

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

// query max news id
func (dao *NewsSpiderDAO) QueryMaxSyncId() (lastId int64, err error) {
	if _, err = dao.db.Model(&lastId).Table(models.TableNameNewsSpider).Max(models.NEWS_SPIDER_COLUMN_ORG_ID).Query(); err != nil {
		return 0, err
	}
	return
}

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