package mail

import (
	"fmt"
	"strings"

	"github.com/google/uuid"
)

var systemFolderSlugs = map[string]string{
	"inbox":   "inbox",
	"sent":    "sent",
	"drafts":  "drafts",
	"trash":   "trash",
	"archive": "archive",
	"spam":    "spam",
}

// folderFilterClause builds a SQL fragment that resolves a folder query param to
// mail_folders rows. System slugs (e.g. "inbox") match folder_type; UUIDs match
// folder id; everything else matches display name case-insensitively.
func folderFilterClause(folder string, argIdx int) (clause string, arg any, ok bool) {
	folder = strings.TrimSpace(folder)
	if folder == "" {
		return "", nil, false
	}
	if _, err := uuid.Parse(folder); err == nil {
		return fmt.Sprintf(" AND m.folder_id = $%d", argIdx), folder, true
	}
	if folderType, known := systemFolderSlugs[strings.ToLower(folder)]; known {
		return fmt.Sprintf(
			" AND m.folder_id IN (SELECT id FROM mail_folders WHERE folder_type = $%d AND account_id = m.account_id)",
			argIdx,
		), folderType, true
	}
	return fmt.Sprintf(
		" AND m.folder_id IN (SELECT id FROM mail_folders WHERE LOWER(name) = LOWER($%d) AND account_id = m.account_id)",
		argIdx,
	), folder, true
}
