package admin_api

import (
	"context"

	"tydata-server/app/main/api/internal/svc"
	"tydata-server/app/main/api/internal/types"
	"tydata-server/app/main/model"
	"tydata-server/common/xerr"

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

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

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

func (l *AdminBatchUpdateApiStatusLogic) AdminBatchUpdateApiStatus(req *types.AdminBatchUpdateApiStatusReq) (resp *types.AdminBatchUpdateApiStatusResp, err error) {
	// 1. 参数验证
	if len(req.Ids) == 0 {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.PARAM_VERIFICATION_ERROR),
			"API ID列表不能为空")
	}
	if req.Status != 0 && req.Status != 1 {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.PARAM_VERIFICATION_ERROR),
			"状态值无效, status: %d", req.Status)
	}

	// 2. 批量更新API状态
	successCount := 0
	for _, id := range req.Ids {
		if id <= 0 {
			continue
		}

		// 查询API是否存在
		api, err := l.svcCtx.AdminApiModel.FindOne(l.ctx, id)
		if err != nil {
			if errors.Is(err, model.ErrNotFound) {
				continue // 跳过不存在的API
			}
			logx.Errorf("查询API失败, err: %v, id: %d", err, id)
			continue
		}

		// 更新状态
		api.Status = req.Status
		_, err = l.svcCtx.AdminApiModel.Update(l.ctx, nil, api)
		if err != nil {
			logx.Errorf("更新API状态失败, err: %v, id: %d", err, id)
			continue
		}

		successCount++
	}

	// 3. 返回结果
	return &types.AdminBatchUpdateApiStatusResp{Success: true}, nil
}
