package missioncode

import (
	"fmt"
	"strconv"
	"strings"
	"time"
)

const (
	prefixStatic = "M-"
	suffixWidth  = 3
)

// BuildPrefix returns the daily mission code prefix, e.g. M-042426-
func BuildPrefix(t time.Time) string {
	return prefixStatic + t.Format("010206") + "-"
}

// NextFromLatest returns next code in sequence using latest code for a day.
// If latest is empty/invalid, sequence starts from 001.
func NextFromLatest(prefix string, latest string) string {
	next := 1
	latest = strings.TrimSpace(latest)
	if strings.HasPrefix(latest, prefix) {
		suffix := strings.TrimPrefix(latest, prefix)
		if n, err := strconv.Atoi(suffix); err == nil && n > 0 {
			next = n + 1
		}
	}
	return fmt.Sprintf("%s%0*d", prefix, suffixWidth, next)
}
