package bookshelve

import (
	"context"
	"server/internal/dao"
	"server/internal/model"
	"server/internal/model/do"
	"server/internal/service"
	"server/utility/ecode"
)

type sBookshelve struct{}

func New() service.IBookshelve {
	return &sBookshelve{}
}

func init() {
	service.RegisterBookshelve(New())
}

// Add 添加书架
func (s *sBookshelve) Add(ctx context.Context, in *model.BookshelveAddIn) (out *model.BookshelveCRUDOut, err error) {
	exist, err := dao.Bookshelves.Ctx(ctx).
		Where(dao.Bookshelves.Columns().UserId, in.UserId).
		Where(dao.Bookshelves.Columns().BookId, in.BookId).
		Exist()
	if err != nil {
		return nil, ecode.Fail.Sub("bookshelve_query_failed")
	}
	if exist {
		return nil, ecode.Params.Sub("bookshelve_exists")
	}
	if _, err := dao.Bookshelves.Ctx(ctx).Data(do.Bookshelves{
		UserId:     in.UserId,
		BookId:     in.BookId,
		ReadStatus: 1, // 默认为正在读
	}).Insert(); err != nil {
		return nil, ecode.Fail.Sub("bookshelve_create_failed")
	}
	return &model.BookshelveCRUDOut{Success: true}, nil
}

// Delete 批量删除书架
func (s *sBookshelve) Delete(ctx context.Context, in *model.BookshelveDelIn) (out *model.BookshelveCRUDOut, err error) {
	if len(in.BookIds) == 0 {
		return nil, ecode.Params.Sub("bookshelve_bookids_empty")
	}
	_, err = dao.Bookshelves.Ctx(ctx).
		Where(dao.Bookshelves.Columns().UserId, in.UserId).
		WhereIn(dao.Bookshelves.Columns().BookId, in.BookIds).
		Delete()
	if err != nil {
		return nil, ecode.Fail.Sub("bookshelve_delete_failed")
	}
	return &model.BookshelveCRUDOut{Success: true}, nil
}

