package admin

import (
	"context"
	"strconv"

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

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

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

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

func (l *SetRolesLogic) SetRoles(req *types.AdminRolesReq) (resp *types.MemberPublic, err error) {
	uid, err := strconv.ParseInt(req.Uid, 10, 64)
	if err != nil {
		return nil, err
	}
	m, err := l.svcCtx.Members.FindByUID(l.ctx, uid)
	if err != nil {
		return nil, err
	}
	wasAdmin, willAdmin := m.IsAdmin(), false
	for _, r := range req.Roles {
		if r == domain.RoleAdmin {
			willAdmin = true
		}
	}
	if wasAdmin && !willAdmin {
		n, countErr := l.svcCtx.Members.CountActiveAdmins(l.ctx)
		if countErr != nil {
			return nil, countErr
		}
		if n <= 1 {
			return nil, domain.ErrLastAdmin
		}
	}
	m.Roles = req.Roles
	m.UpdatedAt = domain.NowNano()
	if err := l.svcCtx.Members.UpdateMember(l.ctx, m); err != nil {
		return nil, err
	}
	return types.MemberFromModel(m), nil
}
