package tenantoverlay

import (
	"context"
	"strings"
	"testing"

	"github.com/DATA-DOG/go-sqlmock"
	sqlmockdrv "github.com/DATA-DOG/go-sqlmock"

	"github.com/nexuscrm/backend/internal/controlplane/packs"
)

// TestPackVerify_FailsOnMissingTenantRows guards that Pack.Verify runs
// in strictMissing mode: on a tenant-enabled deployment, a tenant-spec
// field with no live _System_Field row must surface as a fatal error so
// the operator re-runs apply-tenant.
func TestPackVerify_FailsOnMissingTenantRows(t *testing.T) {
	db, mock, err := sqlmock.New()
	if err != nil {
		t.Fatalf("sqlmock.New: %v", err)
	}
	defer db.Close()

	// Return zero rows — every spec-declared field is "missing".
	mock.ExpectQuery("SELECT o\\.`ApiName`, f\\.`ApiName`, f\\.`Type`, f\\.`Required`, f\\.`DefaultValue`, f\\.`Options`, COALESCE\\(f\\.`IsCustomized`, 0\\) FROM `_System_Field` f JOIN `_System_Object` o .* o\\.`TableType` IN \\(\\?,\\?\\)").
		WithArgs("standard_object", "custom_object").
		WillReturnRows(sqlmockdrv.NewRows([]string{"ApiName", "ApiName", "Type", "Required", "DefaultValue", "Options", "IsCustomized"}))

	pack := testOverlay(t)
	err = pack.Verify(context.Background(), packs.VerifyDeps{DB: db})
	if err == nil {
		t.Fatal("expected tenant Verify to fail when no tenant rows exist, got nil")
	}
	if !strings.Contains(err.Error(), "tenant_objects_spec.json") {
		t.Errorf("expected tenant spec name in error, got: %v", err)
	}
	if err := mock.ExpectationsWereMet(); err != nil {
		t.Fatalf("ExpectationsWereMet: %v", err)
	}
}
