package admin

import (
	"context"
	"strconv"

	"apps/backend/internal/middleware"
	"apps/backend/internal/module/member/domain"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SetSuspendedLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSetSuspendedLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SetSuspendedLogic {
	return &SetSuspendedLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}

func (l *SetSuspendedLogic) SetSuspended(req *types.AdminSuspendReq) (resp *types.MemberPublic, err error) {
	actor, _ := middleware.UIDFrom(l.ctx)
	uid, err := strconv.ParseInt(req.Uid, 10, 64)
	if err != nil {
		return nil, err
	}
	if req.Suspended && uid == actor {
		return nil, domain.ErrSelfSuspend
	}
	m, err := l.svcCtx.Members.FindByUID(l.ctx, uid)
	if err != nil {
		return nil, err
	}
	if req.Suspended && m.IsAdmin() {
		n, countErr := l.svcCtx.Members.CountActiveAdmins(l.ctx)
		if countErr != nil {
			return nil, countErr
		}
		if n <= 1 {
			return nil, domain.ErrLastAdmin
		}
	}
	status := domain.StatusActive
	if req.Suspended {
		status = domain.StatusSuspended
	}
	m, err = l.svcCtx.Auth.UpdateStatus(l.ctx, uid, status)
	if err != nil {
		return nil, err
	}
	return types.MemberFromModel(m), nil
}
