package dao

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

type PrivilegeDAO struct {
	db *sqlca.Engine
}

func NewPrivilegeDAO(db *sqlca.Engine) *PrivilegeDAO {

	return &PrivilegeDAO{
		db: db,
	}
}

func (dao *PrivilegeDAO) Insert(dos *models.PrivilegeDO) (id int64, err error) {
	if id, err = dao.db.Model(&dos).Table(models.TableNamePrivilege).Insert(); err != nil {
		log.Errorf(err.Error())
		return
	}
	return
}

func (dao *PrivilegeDAO) Upsert(do *models.PrivilegeDO, columns ...string) (lastId int64, err error) {
	_, err = dao.db.Model(&do).
		Table(models.TableNamePrivilege).
		Select(models.PRIVILEGE_COLUMN_ID).
		Eq(models.PRIVILEGE_COLUMN_NAME, do.Name).
		Eq(models.PRIVILEGE_COLUMN_LABEL, do.Label).
		Query()
	if err != nil {
		return 0, log.Errorf(err.Error())
	}
	if do.Id == 0 {
		if lastId, err = dao.db.Model(&do).Table(models.TableNamePrivilege).Insert(); err != nil {
			return 0, log.Errorf(err.Error())
		}
	} else {
		if lastId, err = dao.db.Model(&do).Table(models.TableNamePrivilege).Select(columns...).Update(); err != nil {
			return 0, log.Errorf(err.Error())
		}
	}
	return lastId, nil
}

func (dao *PrivilegeDAO) IsTableEmpty() (bool, error) {
	var count int64
	if _, err := dao.db.Model(&count).Table(models.TableNamePrivilege).Count(models.PRIVILEGE_COLUMN_ID).Query(); err != nil {
		return false, log.Errorf(err.Error())
	}
	if count == 0 {
		return true, nil
	}
	return false, nil
}

func (dao *PrivilegeDAO) QueryPrivileges() (privileges models.TreePrivilege) {
	var err error
	var dos []*models.PrivilegeDO
	_, err = dao.db.Model(&dos).Table(models.TableNamePrivilege).Query()
	if err != nil {
		log.Errorf(err.Error())
		return nil
	}
	for _, do := range dos {
		privileges = append(privileges, models.Privilege{
			Label:    do.Label,
			Name:     do.Name,
			Path:     do.Path,
			Children: do.Children,
		})
	}
	return
}
