package admin_order

import (
	"context"
	"time"

	"tydata-server/app/main/api/internal/svc"
	"tydata-server/app/main/api/internal/types"

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

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

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

func (l *AdminRetryAgentProcessLogic) AdminRetryAgentProcess(req *types.AdminRetryAgentProcessReq) (resp *types.AdminRetryAgentProcessResp, err error) {
	// 调用AgentService的重新执行代理处理方法
	err = l.svcCtx.AgentService.RetryAgentProcess(l.ctx, req.Id)
	if err != nil {
		// 检查是否是"已经处理"的错误
		if err.Error() == "代理处理已经成功，无需重新执行" {
			return &types.AdminRetryAgentProcessResp{
				Status:      "already_processed",
				Message:     "代理处理已经成功，无需重新执行",
				ProcessedAt: time.Now().Format("2006-01-02 15:04:05"),
			}, nil
		}

		// 其他错误
		logx.Errorf("重新执行代理处理失败，订单ID: %d, 错误: %v", req.Id, err)
		return &types.AdminRetryAgentProcessResp{
			Status:      "failed",
			Message:     err.Error(),
			ProcessedAt: time.Now().Format("2006-01-02 15:04:05"),
		}, nil
	}

	// 执行成功
	return &types.AdminRetryAgentProcessResp{
		Status:      "success",
		Message:     "代理处理重新执行成功",
		ProcessedAt: time.Now().Format("2006-01-02 15:04:05"),
	}, nil
}
