package whatsapp

import (
	"context"
	"github.com/suyuan32/simple-admin-core/rpc/types/core"
	"wechat-api/ent/whatsapp"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

	"github.com/suyuan32/simple-admin-common/msg/errormsg"

	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *GetWhatsappByIdLogic) GetWhatsappById(req *types.IDReq) (*types.WhatsappInfoResp, error) {
	data, err := l.svcCtx.DB.Whatsapp.Query().Where(whatsapp.ID(req.Id)).WithAgent().Only(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	organizationName := ""
	if data.OrganizationID > 0 {
		departmentInfo, err := l.svcCtx.CoreRpc.GetDepartmentById(l.ctx, &core.IDReq{Id: data.OrganizationID})
		if err != nil {
			l.Error("获取部门信息失败", err)
		}
		if departmentInfo != nil {
			organizationName = *departmentInfo.Name
		}
	}

	var agent types.AgentInfo
	//l.Logger.Infof("agent=%v data=%v\n", data.Edges.Agent, data)
	if data.Edges.Agent != nil {
		agent = types.AgentInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id: &data.AgentID,
			},
			Name:       &data.Edges.Agent.Name,
			Role:       &data.Edges.Agent.Role,
			Status:     &data.Edges.Agent.Status,
			Background: &data.Edges.Agent.Background,
			Examples:   &data.Edges.Agent.Examples,
		}
	}

	return &types.WhatsappInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Code: 0,
			Msg:  errormsg.Success,
		},
		Data: types.WhatsappInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:        &data.ID,
				CreatedAt: pointy.GetPointer(data.CreatedAt.UnixMilli()),
				UpdatedAt: pointy.GetPointer(data.UpdatedAt.UnixMilli()),
			},
			WaId:             &data.WaID,
			Callback:         &data.Callback,
			Account:          &data.Account,
			Phone:            &data.Phone,
			Cc:               &data.Cc,
			PhoneName:        &data.PhoneName,
			OrganizationId:   &data.OrganizationID,
			OrganizationName: &organizationName,
			AgentId:          &data.AgentID,
			AgentInfo:        &agent,
			ApiBase:          &data.APIBase,
			ApiKey:           &data.APIKey,
		},
	}, nil
}
