package crmmap

import (
	"apps/backend/internal/module/crm/domain"
	"apps/backend/internal/types"
)

func Contact(c *domain.Contact) *types.ContactPublic {
	if c == nil {
		return nil
	}
	ids := c.OpportunityIDs
	if ids == nil {
		ids = []string{}
	}
	return &types.ContactPublic{
		Id: c.ID, SourcePlatform: c.SourcePlatform, AuthorHandle: c.AuthorHandle,
		DisplayName: c.DisplayName, Stage: c.Stage, NeedsFollowUp: c.NeedsFollowUp,
		FollowUpDays: c.FollowUpDays, LastTouchAt: c.LastTouchAt,
		OpportunityIds: ids, OpportunityCount: len(ids), MergedFrom: c.MergedFrom,
		TopIntentBand: c.TopIntentBand, TopIntentScore: c.TopIntentScore,
		CreatedAt: c.CreatedAt, UpdatedAt: c.UpdatedAt,
	}
}

func ContactList(list []*domain.Contact) []types.ContactPublic {
	out := make([]types.ContactPublic, 0, len(list))
	for _, c := range list {
		if p := Contact(c); p != nil {
			out = append(out, *p)
		}
	}
	return out
}

func Touch(t *domain.ContactTouch) *types.ContactTouchPublic {
	if t == nil {
		return nil
	}
	return &types.ContactTouchPublic{
		Id: t.ID, ContactId: t.ContactID, Type: t.Type,
		FromStage: t.FromStage, ToStage: t.ToStage, Body: t.Body,
		ActorUid: t.ActorUID, CreatedAt: t.CreatedAt,
	}
}

func TouchList(list []*domain.ContactTouch) []types.ContactTouchPublic {
	out := make([]types.ContactTouchPublic, 0, len(list))
	for _, t := range list {
		if p := Touch(t); p != nil {
			out = append(out, *p)
		}
	}
	return out
}

func FollowUp(f *domain.FollowUp) *types.FollowUpPublic {
	if f == nil {
		return nil
	}
	return &types.FollowUpPublic{
		Id: f.ID, ContactId: f.ContactID, DueAt: f.DueAt, Status: f.Status,
		NotifiedCount: f.NotifiedCount, CreatedAt: f.CreatedAt,
		Contact: types.ContactBrief{},
	}
}

func StageCounts(m map[string]int) []types.StageCount {
	out := make([]types.StageCount, 0, len(m))
	for k, v := range m {
		out = append(out, types.StageCount{Stage: k, Count: v})
	}
	return out
}

func Pagination(page, pageSize int, total int64) types.Pagination {
	if page < 1 {
		page = 1
	}
	if pageSize < 1 {
		pageSize = 20
	}
	tp := int(total) / pageSize
	if int(total)%pageSize != 0 {
		tp++
	}
	return types.Pagination{Page: page, PageSize: pageSize, Total: total, TotalPages: tp}
}
