package crm

import (
	"context"

	"apps/backend/internal/logic/crmmap"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *GetContactLogic) GetContact(req *types.GetContactReq) (*types.ContactDetailData, error) {
	uid, err := ownerUID(l.ctx)
	if err != nil {
		return nil, err
	}
	c, touches, total, err := l.svcCtx.Crm.GetContact(l.ctx, uid, int64(req.Page), int64(req.PageSize), req.Id)
	if err != nil {
		return nil, err
	}
	briefs := make([]types.ContactOpportunityBrief, 0)
	for _, raw := range l.svcCtx.Crm.OpportunityBriefs(l.ctx, uid, c.OpportunityIDs) {
		b := types.ContactOpportunityBrief{}
		if v, ok := raw["id"].(string); ok {
			b.Id = v
		}
		if v, ok := raw["permalink"].(string); ok {
			b.Permalink = v
		}
		if v, ok := raw["text"].(string); ok {
			b.Text = v
		}
		if v, ok := raw["intent_score"].(int); ok {
			b.IntentScore = v
		}
		if v, ok := raw["intent_band"].(string); ok {
			b.IntentBand = v
		}
		if v, ok := raw["created_at"].(int64); ok {
			b.CreatedAt = v
		}
		briefs = append(briefs, b)
	}
	return &types.ContactDetailData{
		Contact:       *crmmap.Contact(c),
		Touches:       crmmap.TouchList(touches),
		Pagination:    crmmap.Pagination(req.Page, req.PageSize, total),
		Opportunities: briefs,
	}, nil
}
