package main

import (
	"errors"
	"fmt"
	"os"
	"strings"

	"git.tilde.town/tildetown/town/email"
	"git.tilde.town/tildetown/town/invites"
)

const emailText = `hello!

You applied to https://tilde.town at some point and your application has been approved ^_^

Your invite code is: %s

To redeem your code, please open a terminal and run:

ssh welcome@tilde.town

You'll fill in details like your desired username and SSH public key.

This page has information on what SSH is and how to use it, including how to create an ssh key pair which you'll need to access your town account: https://tilde.town/wiki/getting-started/ssh.html

If you end up stuck, e-mail root@tilde.town with any questions.

See you on the server,
~vilmibm`

func loadPassword() (string, error) {
	f, err := os.Open("/town/docs/smtp.pw")
	if err != nil {
		return "", fmt.Errorf("could not open smtp password file: %w", err)
	}

	pw := make([]byte, 100)

	n, err := f.Read(pw)
	if err != nil {
		return "", fmt.Errorf("could not read smtp password file: %w", err)
	}
	if n == 0 {
		return "", errors.New("smtp password file was empty")
	}

	return strings.TrimSpace(string(pw[0:n])), nil
}

func sendInviteEmail(invite invites.Invite) error {
	pw, err := loadPassword()
	if err != nil {
		return fmt.Errorf("could not read password: %w", err)
	}

	body := fmt.Sprintf(emailText, invite.Code)

	mailer := email.NewExternalMailer(pw)
	return mailer.Send(
		invite.Email,
		"your tilde.town application was accepted",
		body)
}
