package book

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/book"
	bookReq "github.com/flipped-aurora/gin-vue-admin/server/model/book/request"
	commonReq "github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
)

type BookAuthorRelationService struct{}

func (s *BookAuthorRelationService) CreateBookAuthorRelation(item book.BookAuthorRelation) error {
	item = applyBookAuthorRelationDefaults(item)
	if err := validateBookAuthorRelation(item); err != nil {
		return err
	}
	return global.GVA_DB.Create(&item).Error
}

func (s *BookAuthorRelationService) DeleteBookAuthorRelation(item book.BookAuthorRelation) error {
	return global.GVA_DB.Delete(&item).Error
}

func (s *BookAuthorRelationService) DeleteBookAuthorRelationByIds(ids commonReq.IdsReq) error {
	return deleteByIDs[book.BookAuthorRelation](ids.Ids)
}

func (s *BookAuthorRelationService) UpdateBookAuthorRelation(item book.BookAuthorRelation) error {
	if err := validateBookAuthorRelation(item); err != nil {
		return err
	}
	return global.GVA_DB.Save(&item).Error
}

func (s *BookAuthorRelationService) GetBookAuthorRelation(id uint) (item book.BookAuthorRelation, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&item).Error
	return
}

func (s *BookAuthorRelationService) GetBookAuthorRelationInfoList(info bookReq.BookAuthorRelationSearch) (list []book.BookAuthorRelation, total int64, err error) {
	db := global.GVA_DB.Model(&book.BookAuthorRelation{})
	if info.BookID != nil {
		db = db.Where("book_id = ?", *info.BookID)
	}
	if info.AuthorID != nil {
		db = db.Where("author_id = ?", *info.AuthorID)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Scopes(paginate(info.PageInfo)).Order("book_id asc, author_sort asc, id desc").Find(&list).Error
	return
}
