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 BookChapterService struct{}

func (s *BookChapterService) CreateBookChapter(item book.BookChapter) error {
	if err := validateBookChapter(item); err != nil {
		return err
	}
	return global.GVA_DB.Create(&item).Error
}

func (s *BookChapterService) DeleteBookChapter(item book.BookChapter) error {
	return global.GVA_DB.Delete(&item).Error
}

func (s *BookChapterService) DeleteBookChapterByIds(ids commonReq.IdsReq) error {
	return deleteByIDs[book.BookChapter](ids.Ids)
}

func (s *BookChapterService) UpdateBookChapter(item book.BookChapter) error {
	if err := validateBookChapter(item); err != nil {
		return err
	}
	return global.GVA_DB.Save(&item).Error
}

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

func (s *BookChapterService) GetBookChapterInfoList(info bookReq.BookChapterSearch) (list []book.BookChapter, total int64, err error) {
	db := global.GVA_DB.Model(&book.BookChapter{})
	if info.BookID != nil {
		db = db.Where("book_id = ?", *info.BookID)
	}
	if info.IsReadable != nil {
		db = db.Where("is_readable = ?", *info.IsReadable)
	}
	if info.IsEnabled != nil {
		db = db.Where("is_enabled = ?", *info.IsEnabled)
	}
	if info.Keyword != "" {
		db = db.Where("title LIKE ?", "%"+info.Keyword+"%")
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Scopes(paginate(info.PageInfo)).Order("book_id asc, chapter_no asc").Find(&list).Error
	return
}
