package businessscope

import (
	"strings"
	"testing"
)

func TestCandidateQueryUsesCompletedLifecycleFactsInsteadOfAggregateReturnTime(t *testing.T) {
	assertions := []string{
		"FROM delivery_vehicle dv",
		"dv.delivery_status IN (2, 3)",
		"FROM return_vehicle_task rt",
		"rt.status IN (2, 3, 5)",
		"FROM delivery_vehicle newer",
		"LEFT JOIN vehicle_lease_order_record r",
	}
	for _, expected := range assertions {
		if !strings.Contains(candidateQuery, expected) {
			t.Fatalf("candidate query missing %q", expected)
		}
	}
	if strings.Contains(candidateQuery, "r.last_return_time") {
		t.Fatal("candidate query must not trust aggregate last_return_time written by return drafts")
	}
}

func TestValidateReadOnlyGrantsAllowsOnlyRequiredTableSelects(t *testing.T) {
	grants := []string{
		"GRANT USAGE ON *.* TO `reader`@`%`",
		"GRANT SELECT ON `ln_asset_management`.`vehicle_lease_order_record` TO `reader`@`%`",
		"GRANT SELECT ON `ln_asset_management`.`delivery_vehicle` TO `reader`@`%`",
		"GRANT SELECT ON `ln_asset_management`.`return_vehicle_task` TO `reader`@`%`",
		"GRANT SELECT ON `ln_asset_management`.`vehicle_info` TO `reader`@`%`",
		"GRANT SELECT ON `ln_asset_management`.`customer_info` TO `reader`@`%`",
		"GRANT SELECT ON `ln_asset_management`.`vehicle_lease_contract_info` TO `reader`@`%`",
		"GRANT SELECT ON `ln_asset_management`.`vehicle_status` TO `reader`@`%`",
	}
	if err := ValidateReadOnlyGrants(grants); err != nil {
		t.Fatalf("read-only grants rejected: %v", err)
	}
}

func TestValidateReadOnlyGrantsRejectsBroadOrWritePrivileges(t *testing.T) {
	cases := [][]string{
		{"GRANT ALL PRIVILEGES ON `ln_asset_management`.* TO `reader`@`%`"},
		{"GRANT SELECT, UPDATE ON `ln_asset_management`.* TO `reader`@`%`"},
		{"GRANT SELECT ON *.* TO `reader`@`%`"},
		{"GRANT SELECT ON `ln_asset_management`.* TO `reader`@`%`"},
		{"GRANT SELECT ON `ry-cloud`.`sys_user` TO `reader`@`%`"},
		{"GRANT SHOW VIEW ON `ln_asset_management`.`vehicle_info` TO `reader`@`%`"},
		{"GRANT PROCESS, REPLICATION CLIENT ON *.* TO `reader`@`%`"},
		{"GRANT `scope_reader_role`@`%` TO `reader`@`%`"},
		{"SET DEFAULT ROLE `scope_reader_role`@`%` TO `reader`@`%`"},
	}
	for _, grants := range cases {
		if err := ValidateReadOnlyGrants(grants); err == nil {
			t.Fatalf("unsafe grants accepted: %#v", grants)
		}
	}
}
