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

func (s *BookReadRecordService) CreateBookReadRecord(item book.BookReadRecord) error {
	if err := validateBookReadRecord(item); err != nil {
		return err
	}
	return global.GVA_DB.Create(&item).Error
}

func (s *BookReadRecordService) DeleteBookReadRecord(item book.BookReadRecord) error {
	return global.GVA_DB.Delete(&item).Error
}

func (s *BookReadRecordService) DeleteBookReadRecordByIds(ids commonReq.IdsReq) error {
	return deleteByIDs[book.BookReadRecord](ids.Ids)
}

func (s *BookReadRecordService) UpdateBookReadRecord(item book.BookReadRecord) error {
	if err := validateBookReadRecord(item); err != nil {
		return err
	}
	return global.GVA_DB.Save(&item).Error
}

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

func (s *BookReadRecordService) GetBookReadRecordInfoList(info bookReq.BookReadRecordSearch) (list []book.BookReadRecord, total int64, err error) {
	db := global.GVA_DB.Model(&book.BookReadRecord{})
	if info.MemberUserID != nil {
		db = db.Where("member_user_id = ?", *info.MemberUserID)
	}
	if info.BookID != nil {
		db = db.Where("book_id = ?", *info.BookID)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Scopes(paginate(info.PageInfo)).Order("last_read_at desc, id desc").Find(&list).Error
	return
}
