package mail

import (
	"testing"

	"github.com/google/uuid"
)

func TestFolderFilterClause(t *testing.T) {
	id := uuid.NewString()

	tests := []struct {
		name    string
		folder  string
		wantOK  bool
		wantArg any
		wantSQL string
	}{
		{name: "empty", folder: "", wantOK: false},
		{name: "inbox slug", folder: "inbox", wantOK: true, wantArg: "inbox", wantSQL: "folder_type"},
		{name: "Inbox slug", folder: "Inbox", wantOK: true, wantArg: "inbox", wantSQL: "folder_type"},
		{name: "uuid", folder: id, wantOK: true, wantArg: id, wantSQL: "m.folder_id = $1"},
		{name: "custom name", folder: "Factures", wantOK: true, wantArg: "Factures", wantSQL: "LOWER(name)"},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			clause, arg, ok := folderFilterClause(tc.folder, 1)
			if ok != tc.wantOK {
				t.Fatalf("ok = %v, want %v", ok, tc.wantOK)
			}
			if !tc.wantOK {
				return
			}
			if arg != tc.wantArg {
				t.Fatalf("arg = %v, want %v", arg, tc.wantArg)
			}
			if !stringsContains(clause, tc.wantSQL) {
				t.Fatalf("clause = %q, want fragment %q", clause, tc.wantSQL)
			}
		})
	}
}

func stringsContains(s, sub string) bool {
	return len(s) >= len(sub) && (s == sub || len(sub) == 0 || indexOf(s, sub) >= 0)
}

func indexOf(s, sub string) int {
	for i := 0; i+len(sub) <= len(s); i++ {
		if s[i:i+len(sub)] == sub {
			return i
		}
	}
	return -1
}
