package commerce

import (
	"strings"
	"testing"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func TestBoolStatus(t *testing.T) {
	tests := []struct {
		raw  string
		want bool
		ok   bool
	}{
		{raw: "enabled", want: true, ok: true},
		{raw: "active", want: true, ok: true},
		{raw: "1", want: true, ok: true},
		{raw: "disabled", want: false, ok: true},
		{raw: "inactive", want: false, ok: true},
		{raw: "0", want: false, ok: true},
		{raw: "all", want: false, ok: false},
	}
	for _, tt := range tests {
		t.Run(tt.raw, func(t *testing.T) {
			got, ok := boolStatus(tt.raw)
			if got != tt.want || ok != tt.ok {
				t.Fatalf("boolStatus(%q) = (%v, %v), want (%v, %v)", tt.raw, got, ok, tt.want, tt.ok)
			}
		})
	}
}

func TestApplyAdminRawListSpecFiltersKnownTables(t *testing.T) {
	db := dryRunMySQL(t)
	stmt := applyAdminRawListSpec(db.Table("agent_tiers"), "agent_tiers", AdminListQuery{
		Status: "enabled",
		Search: "lv1",
	}).Find(&[]map[string]any{}).Statement

	sql := stmt.SQL.String()
	for _, want := range []string{"enabled = ?", "name LIKE ?", "code LIKE ?", "description LIKE ?", "ORDER BY sort_order ASC, id DESC"} {
		if !strings.Contains(sql, want) {
			t.Fatalf("generated SQL missing %q: %s", want, sql)
		}
	}
	if len(stmt.Vars) != 4 {
		t.Fatalf("vars length = %d, want 4: %#v", len(stmt.Vars), stmt.Vars)
	}
	if stmt.Vars[0] != true {
		t.Fatalf("status var = %#v, want true", stmt.Vars[0])
	}
}

func TestApplyAdminRawListSpecLeavesUnknownTablesConservative(t *testing.T) {
	db := dryRunMySQL(t)
	stmt := applyAdminRawListSpec(db.Table("unknown_table"), "unknown_table", AdminListQuery{
		Status: "enabled",
		Search: "needle",
	}).Find(&[]map[string]any{}).Statement

	sql := stmt.SQL.String()
	if strings.Contains(sql, "LIKE") || strings.Contains(sql, "enabled = ?") {
		t.Fatalf("unknown table should not receive dynamic filters: %s", sql)
	}
	if !strings.Contains(sql, "ORDER BY id DESC") {
		t.Fatalf("unknown table should keep default ordering: %s", sql)
	}
}

func dryRunMySQL(t *testing.T) *gorm.DB {
	t.Helper()
	db, err := gorm.Open(mysql.New(mysql.Config{
		DSN:                       "gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True&loc=Local",
		SkipInitializeWithVersion: true,
	}), &gorm.Config{DryRun: true, DisableAutomaticPing: true})
	if err != nil {
		t.Fatalf("open dry-run mysql: %v", err)
	}
	return db
}
