package crm

import (
	"context"

	"apps/backend/internal/logic/crmmap"
	"apps/backend/internal/module/crm/domain"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *ListFollowUpsLogic) ListFollowUps(req *types.ListFollowUpsReq) (*types.FollowUpListData, error) {
	uid, err := ownerUID(l.ctx)
	if err != nil {
		return nil, err
	}
	list, total, err := l.svcCtx.Crm.ListFollowUps(l.ctx, uid, domain.FollowUpListFilter{
		Status: req.Status, Page: req.Page, PageSize: req.PageSize,
	})
	if err != nil {
		return nil, err
	}
	out := make([]types.FollowUpPublic, 0, len(list))
	// 同一聯絡人常有多筆追蹤；快取避免整頁重複查同一筆
	briefs := make(map[string]types.ContactBrief, len(list))
	for _, f := range list {
		p := crmmap.FollowUp(f)
		if p == nil {
			continue
		}
		brief, cached := briefs[f.ContactID]
		if !cached {
			if c, cerr := l.svcCtx.Crm.GetContactOnly(l.ctx, uid, f.ContactID); cerr == nil && c != nil {
				brief = types.ContactBrief{
					Id: c.ID, SourcePlatform: c.SourcePlatform, AuthorHandle: c.AuthorHandle,
					DisplayName: c.DisplayName, Stage: c.Stage,
				}
			}
			briefs[f.ContactID] = brief
		}
		p.Contact = brief
		out = append(out, *p)
	}
	return &types.FollowUpListData{List: out, Pagination: crmmap.Pagination(req.Page, req.PageSize, total)}, nil
}
