package app_test

import (
	"context"
	"testing"

	"hyapp/pkg/xerr"
	"hyapp/services/user-service/internal/testutil/mysqltest"
)

func TestResolveAppPrefersExplicitAppCodeOverPackagePlatform(t *testing.T) {
	repo := mysqltest.NewRepository(t).Repository.AppRepository()

	resolved, err := repo.ResolveApp(context.Background(), "lalu", "com.org.laluparty", "ios")
	if err != nil {
		t.Fatalf("ResolveApp with explicit app_code failed: %v", err)
	}
	if resolved.AppCode != "lalu" {
		t.Fatalf("app_code mismatch: %+v", resolved)
	}
}

func TestResolveAppUsesWildcardPlatformForPackageOnlyRequests(t *testing.T) {
	repo := mysqltest.NewRepository(t).Repository.AppRepository()

	resolved, err := repo.ResolveApp(context.Background(), "", "com.org.laluparty", "ios")
	if err != nil {
		t.Fatalf("ResolveApp with wildcard platform failed: %v", err)
	}
	if resolved.AppCode != "lalu" || resolved.Platform != "" {
		t.Fatalf("wildcard app mismatch: %+v", resolved)
	}
}

func TestResolveAppSupportsFamiPackage(t *testing.T) {
	repo := mysqltest.NewRepository(t).Repository.AppRepository()

	resolved, err := repo.ResolveApp(context.Background(), "", "com.chat.fami", "android")
	if err != nil {
		t.Fatalf("ResolveApp with fami package failed: %v", err)
	}
	if resolved.AppCode != "fami" || resolved.PackageName != "com.chat.fami" || resolved.Status != "active" {
		t.Fatalf("fami app mismatch: %+v", resolved)
	}
}

func TestResolveAppRejectsUnsupportedPackage(t *testing.T) {
	repo := mysqltest.NewRepository(t).Repository.AppRepository()

	_, err := repo.ResolveApp(context.Background(), "", "com.unsupported.app", "ios")
	if xerr.CodeOf(err) != xerr.InvalidArgument {
		t.Fatalf("expected invalid argument for unsupported package, got %v", err)
	}
}

func TestListAppsReturnsOnlyActiveAppsInStableOrder(t *testing.T) {
	repo := mysqltest.NewRepository(t).Repository.AppRepository()

	apps, err := repo.ListApps(context.Background())
	if err != nil {
		t.Fatalf("ListApps failed: %v", err)
	}
	if len(apps) == 0 {
		t.Fatal("ListApps must return seeded active apps")
	}
	for index, app := range apps {
		if app.Status != "active" {
			t.Fatalf("inactive app leaked into registry: %+v", app)
		}
		if index > 0 && apps[index-1].AppCode > app.AppCode {
			t.Fatalf("apps must be sorted by app_code: %+v", apps)
		}
	}
}
