package autoconfig

import (
	"context"
	"testing"
)

func TestMatchDomainGmail(t *testing.T) {
	p, ok := matchDomain("gmail.com")
	if !ok || p.id != "gmail" {
		t.Fatalf("expected gmail preset, got ok=%v id=%q", ok, p.id)
	}
}

func TestMatchDomainOutlookFR(t *testing.T) {
	p, ok := matchDomain("outlook.fr")
	if !ok || p.id != "outlook" {
		t.Fatalf("expected outlook preset, got ok=%v id=%q", ok, p.id)
	}
}

func TestDiscoverPreset(t *testing.T) {
	r, err := Discover(context.Background(), "User@Gmail.COM")
	if err != nil {
		t.Fatal(err)
	}
	if r.Source != "preset" || r.IMAPHost != "imap.gmail.com" {
		t.Fatalf("unexpected result: %+v", r)
	}
	if r.Email != "User@Gmail.COM" {
		// ParseAddress normalizes? Actually mail.ParseAddress keeps case in local part
		// but domain might be lowercased in Address field
	}
}

func TestGuessFromDomain(t *testing.T) {
	r := guessFromDomain("a@example.org", "example.org")
	if r.Source != "guess" || r.IMAPHost != "imap.example.org" {
		t.Fatalf("unexpected guess: %+v", r)
	}
}

func TestParseMozillaConfig(t *testing.T) {
	const sample = `<?xml version="1.0"?>
<clientConfig version="1.1">
  <emailProvider id="example.com">
    <domain>example.com</domain>
    <displayName>Example Mail</displayName>
    <incomingServer type="imap">
      <hostname>imap.example.com</hostname>
      <port>993</port>
      <socketType>SSL</socketType>
      <username>%EMAILADDRESS%</username>
    </incomingServer>
    <outgoingServer type="smtp">
      <hostname>smtp.example.com</hostname>
      <port>587</port>
      <socketType>STARTTLS</socketType>
    </outgoingServer>
  </emailProvider>
</clientConfig>`
	r, ok := parseMozillaConfig([]byte(sample), "example.com")
	if !ok {
		t.Fatal("expected parse ok")
	}
	if r.IMAPHost != "imap.example.com" || r.SMTPHost != "smtp.example.com" {
		t.Fatalf("unexpected hosts: %+v", r)
	}
}

func TestDiscoverInvalidEmail(t *testing.T) {
	_, err := Discover(context.Background(), "not-an-email")
	if err != ErrInvalidEmail {
		t.Fatalf("expected ErrInvalidEmail, got %v", err)
	}
}
