package crm

import (
	"context"
	"strings"

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

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

func (l *ListContactsLogic) ListContacts(req *types.ListContactsReq) (*types.ContactListData, error) {
	uid, err := ownerUID(l.ctx)
	if err != nil {
		return nil, err
	}
	f := domain.ContactListFilter{Query: req.Query, Stage: req.Stage, Band: req.Band, Sort: req.Sort, Page: req.Page, PageSize: req.PageSize}
	switch strings.ToLower(req.FollowUp) {
	case "true", "1":
		v := true
		f.FollowUp = &v
	case "false", "0":
		v := false
		f.FollowUp = &v
	}
	list, total, counts, err := l.svcCtx.Crm.ListContacts(l.ctx, uid, f)
	if err != nil {
		return nil, err
	}
	return &types.ContactListData{
		List: crmmap.ContactList(list), Pagination: crmmap.Pagination(req.Page, req.PageSize, total),
		StageCounts: crmmap.StageCounts(counts),
	}, nil
}
