package main

import (
	"crypto/tls"
	"fmt"
	"log"
	"os"

	"github.com/emersion/go-imap/client"
)

func main() {
	if len(os.Args) != 5 {
		fmt.Println("Usage: imap-test <host> <port> <username> <password>")
		fmt.Println("Example: imap-test 10.10.11.30 993 agus.wahyudi Pnd77net!")
		os.Exit(1)
	}

	host := os.Args[1]
	port := os.Args[2]
	username := os.Args[3]
	password := os.Args[4]

	addr := fmt.Sprintf("%s:%s", host, port)
	fmt.Printf("Testing IMAP connection to %s\n", addr)
	fmt.Printf("Username: %s\n", username)
	fmt.Printf("Password: %s\n", password)

	// Connect with TLS
	tlsConfig := &tls.Config{
		ServerName:         host,
		InsecureSkipVerify: true,
	}

	c, err := client.DialTLS(addr, tlsConfig)
	if err != nil {
		log.Fatalf("Failed to connect: %v", err)
	}
	defer c.Close()

	fmt.Println("✓ Connected successfully")

	// Get capabilities
	caps, err := c.Capability()
	if err != nil {
		fmt.Printf("Failed to get capabilities: %v\n", err)
	} else {
		fmt.Printf("Server capabilities: %v\n", caps)
	}

	// Try LOGIN
	fmt.Println("Trying LOGIN...")
	if err := c.Login(username, password); err != nil {
		fmt.Printf("✗ LOGIN failed: %v\n", err)

		// Try different username formats
		testUsernames := []string{
			username + "@adastra.id",
			username + "@mail.adastra.id",
			username,
		}

		for _, testUser := range testUsernames {
			if testUser == username {
				continue // already tried
			}
			fmt.Printf("Trying LOGIN with username: %s\n", testUser)
			if err := c.Login(testUser, password); err != nil {
				fmt.Printf("✗ LOGIN failed with %s: %v\n", testUser, err)
			} else {
				fmt.Printf("✓ LOGIN succeeded with username: %s\n", testUser)
				return
			}
		}
	} else {
		fmt.Printf("✓ LOGIN succeeded with username: %s\n", username)
	}
}
