package Wx

import (
	"context"
	"wechat-api/ent"
	"wechat-api/ent/wx"

	"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 GetWxByIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *GetWxByIdLogic) GetWxById(req *types.IDReq) (resp *types.WxInfoResp, err error) {
	isAdmin := l.ctx.Value("isAdmin").(bool)
	var data *ent.Wx
	if isAdmin {
		data, err = l.svcCtx.DB.Wx.Query().
			Where(
				wx.IDEQ(req.Id),
			).
			WithAgent().
			Only(l.ctx)
	} else {
		organizationId := l.ctx.Value("organizationId").(uint64)
		data, err = l.svcCtx.DB.Wx.Query().
			Where(
				wx.IDEQ(req.Id),                   // Filter by ID
				wx.OrganizationID(organizationId), // Additional filter by organizationId
			).
			WithAgent().
			Only(l.ctx)
	}
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	agent := types.AgentInfo{
		BaseIDInfo: types.BaseIDInfo{
			Id:        &data.AgentID,
			CreatedAt: pointy.GetPointer(data.Edges.Agent.CreatedAt.UnixMilli()),
			UpdatedAt: pointy.GetPointer(data.Edges.Agent.UpdatedAt.UnixMilli()),
		},
		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.WxInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Code: 0,
			Msg:  errormsg.Success,
		},
		Data: types.WxInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:        &data.ID,
				CreatedAt: pointy.GetPointer(data.CreatedAt.UnixMilli()),
				UpdatedAt: pointy.GetPointer(data.UpdatedAt.UnixMilli()),
			},
			Status:         &data.Status,
			ServerId:       &data.ServerID,
			Port:           &data.Port,
			ProcessId:      &data.ProcessID,
			Callback:       &data.Callback,
			Wxid:           &data.Wxid,
			Account:        &data.Account,
			Nickname:       &data.Nickname,
			Tel:            &data.Tel,
			HeadBig:        &data.HeadBig,
			OrganizationId: &data.OrganizationID,
			AgentId:        &data.AgentID,
			AgentInfo:      &agent,
			Ctype:          &data.Ctype,
		},
	}, nil
}
