package platform

import (
	"context"
	"errors"
	"fmt"

	"source.gleipnir.technology/Gleipnir/nidus-sync/db"
	querycomms "source.gleipnir.technology/Gleipnir/nidus-sync/db/query/comms"
	"source.gleipnir.technology/Gleipnir/nidus-sync/platform/types"
)

func MessagesForContact(ctx context.Context, contact_id int64) ([]types.Message, error) {
	//emails, err := querycomms.EmailsFromContactID
	txn := db.PGInstance.PGXPool
	contact_phone, err := querycomms.ContactPhoneFromContactID(ctx, txn, contact_id)
	if err != nil {
		if errors.Is(err, db.ErrNoRows) {
			return []types.Message{}, nil
		}
		return nil, fmt.Errorf("contact_phone from contact id %d: %w", contact_id, err)
	}
	texts, err := querycomms.TextLogsFromPhoneNumber(ctx, txn, contact_phone.E164)
	if err != nil {
		return nil, fmt.Errorf("text log from contact id %d: %w", contact_id, err)
	}
	results := make([]types.Message, len(texts))
	for i, text := range texts {
		results[i] = types.Message{
			Content:     text.Content,
			Created:     text.Created,
			Destination: text.Destination,
			Source:      text.Source,
			Type:        types.MessageTypeText,
		}
	}
	return results, err
}
