package pages

import (
	"context"
	"time"

	"bsm/full/module/base/cms/internal/impl"
	"bsm/full/module/base/cms/internal/models"
	pb "bsm/full/module/base/cms/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/service"
	"git.apinb.com/bsm-sdk/core/vars"
	"gorm.io/gorm"
)

// 删除文章
func Delete(ctx context.Context, in *pb.IdentRequest) (reply *pb.StatusReply, err error) {
	// parse authorization meta.
	_, err = service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	if in.Identity == "" {
		return nil, errcode.ErrInvalidArgument
	}
	err = DeletePages(in.Identity)
	if err != nil {
		return nil, errcode.ErrDB
	}
	return &pb.StatusReply{
		Code:    0,
		Message: vars.OK,
		Timeseq: time.Now().UnixMilli(),
	}, nil

}

func DeletePages(identity string) (err error) {
	return impl.DBService.Transaction(func(tx *gorm.DB) error {
		if err = tx.Where("identity = ?", identity).Delete(&models.CmsPages{}).Error; err != nil {
			return err
		}
		if err = tx.Where("pages_identity = ?", identity).Delete(&models.CmsRelateTags{}).Error; err != nil {
			return err
		}
		if err = tx.Where("pages_identity = ?", identity).Delete(&models.CmsAccessory{}).Error; err != nil {
			return err
		}
		return nil
	})
}
