package smtp

import (
	"context"
	"io"
	"log"

	"github.com/emersion/go-smtp"

	"ur.gs/crockery/internal/store"
)

type Server interface {
	Run()

	io.Closer
}

func NewServer(cancel context.CancelFunc, datastore store.Interface, submission bool) Server {
	out := &concrete{
		cancel: cancel,
		store:  datastore,
	}

	out.server = smtp.NewServer(out)
	out.server.Domain = datastore.Domain()
	out.server.TLSConfig = datastore.TLSConfig()

	if submission {
		out.server.Addr = ":587"
	} else {
		out.server.Addr = ":25"
	}

	return out
}

type concrete struct {
	cancel context.CancelFunc
	store  store.Interface
	server *smtp.Server
}

func (c *concrete) Run() {
	if err := c.server.ListenAndServe(); err != nil {
		log.Printf("Error serving SMTP %s: %v", c.server.Addr, err)
	} else {
		log.Printf("Stopped listening on SMTP %s", c.server.Addr)
	}

	c.cancel()
}

// backend implementation for go-smtp
func (c *concrete) Login(string, string) (smtp.User, error) {
	return nil, nil
}

func (c *concrete) Close() error {
	c.cancel() // FIXME: this doesn't touch the server

	return nil
}
