using ESuite.UI.E2E.Helpers;
using ESuite.UI.E2E.Pages;
using OpenQA.Selenium;

namespace ESuite.UI.E2E.StepDefinitions
{
    [Binding]
    public class ErrorLogsVerificationStepDefinitions
    {

        private readonly IWebDriver driver;
        private readonly BasicPage basicPage;
        private readonly ScenarioContext _scenarioContext;
        private readonly APIHelper apiHelper;
        private readonly ConfigHelper configHelper;
        public ErrorLogsVerificationStepDefinitions(ScenarioContext scenarioContext)
        {
            driver = WebDriverHelper.GetWebDriver();
            basicPage = new BasicPage(driver);
            _scenarioContext = scenarioContext;
            apiHelper = new APIHelper(_scenarioContext);
            configHelper = new ConfigHelper();
        }

        [Given(@"I create a new domain with insufficient info via API call")]
        public async Task GivenICreateANewDomainWithInsufficientInfoViaAPICall()
        {
            int maxAttempts = 2;
            int currentAttempt = 0;
            string content;
            HttpResponseMessage? response;

            do
            {
                string token = await apiHelper.GetAuthToken();
                string url = $"{configHelper.APIUrl}/api/Domain/domain";
                string payload = $@"
                    {{
                        ""name"": 123,  
                        ""guid"": ""3fa85f64-5717-4562-b3fc-2c963f66afa6""
                    }}";  // Bad Payload. Backend expects to get 'name' in string format.

                response = await apiHelper.SendAuthenticatedRequest(url, token, payload, "POST");
                content = await response.Content.ReadAsStringAsync();
                if (!string.IsNullOrEmpty(content))
                {
                    string instanceID = APIHelper.GetFieldValueFromJSONResponse("Instance", content);
                    _scenarioContext["ErrorInstanceID"] = instanceID;
                    break;
                }

                currentAttempt++;
            } while (currentAttempt < maxAttempts);

            if (string.IsNullOrEmpty(content))
            {
                throw new Exception($"Failed to get a valid response after {currentAttempt} attempts.");
            }
        }

        [Then(@"I verifying newly created exception on the Error Logs page")]
        public void ThenIVerifyingNewlyCreatedExceptionOnTheErrorLogsPage()
        {
            BasicPage.ClickOnDropdownMenuItem("Error Logs", "Support");
            BasicPage.SearchObjectNameInTableViaSearchInputField(_scenarioContext["ErrorInstanceID"].ToString()!,By.Id("id"));
        }

    }
}
