package mail

import (
	"context"
	"fmt"
	"strings"
)

func identityDisplayName(name, email string) string {
	if n := strings.TrimSpace(name); n != "" {
		return n
	}
	if i := strings.Index(email, "@"); i > 0 {
		return email[:i]
	}
	return strings.TrimSpace(email)
}

func defaultSignatureName(email string) string {
	return fmt.Sprintf("Signature — %s", strings.TrimSpace(email))
}

func (s *Service) ensureIdentityDefaultSignature(ctx context.Context, externalID, email string) (string, error) {
	return s.CreateSignature(ctx, externalID, &createSignatureRequest{
		Name: defaultSignatureName(email),
		HTML: "",
	})
}

// bootstrapAccountDefaults creates the default send identity and linked signature for a new mail account.
func (s *Service) bootstrapAccountDefaults(ctx context.Context, externalID, accountID, email, accountName string) error {
	sigID, err := s.ensureIdentityDefaultSignature(ctx, externalID, email)
	if err != nil {
		return err
	}
	_, err = s.CreateIdentity(ctx, externalID, accountID, &createIdentityRequest{
		Email:              strings.TrimSpace(email),
		Name:               identityDisplayName(accountName, email),
		IsDefault:          true,
		DefaultSignatureID: sigID,
		ReplyToAddrs:       []string{},
	})
	return err
}
