package admin

import (
	"context"
	"strconv"

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

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

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

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

func (l *SetStatusLogic) SetStatus(req *types.AdminStatusReq) (resp *types.MemberPublic, err error) {
	actor, _ := middleware.UIDFrom(l.ctx)
	uid, err := strconv.ParseInt(req.Uid, 10, 64)
	if err != nil {
		return nil, err
	}
	status := req.Status
	switch status {
	case domain.StatusActive, domain.StatusSuspended, domain.StatusUnverified, domain.StatusUninitialized:
	default:
		return nil, response.Biz(400, 400001, "invalid member status")
	}
	if status != domain.StatusActive {
		if uid == actor {
			return nil, domain.ErrSelfSuspend
		}
		member, findErr := l.svcCtx.Members.FindByUID(l.ctx, uid)
		if findErr != nil {
			return nil, findErr
		}
		if member.IsAdmin() {
			n, countErr := l.svcCtx.Members.CountActiveAdmins(l.ctx)
			if countErr != nil {
				return nil, countErr
			}
			if n <= 1 {
				return nil, domain.ErrLastAdmin
			}
		}
	}
	m, err := l.svcCtx.Auth.UpdateStatus(l.ctx, uid, status)
	if err != nil {
		return nil, err
	}
	return types.MemberFromModel(m), nil
}
