from selenium.webdriver.common.by import By

from .base import FunctionalTest
from apps.lyric.models import User


class AdminLoginTest(FunctionalTest):
    def setUp(self):
        super().setUp()
        self.superuser = User.objects.create_superuser(
            email="admin@example.com",
            password="correct-password",
        )

    def test_can_access_admin(self):
        self.browser.get(self.live_server_url + "/admin/")

        self.wait_for(lambda: self.browser.find_element(By.ID, "id_username"))
        self.browser.find_element(By.ID, "id_username").send_keys("admin@example.com")
        self.browser.find_element(By.ID, "id_password").send_keys("correct-password")
        self.browser.find_element(By.CSS_SELECTOR, "input[type=submit]").click()

        # Wait on the post-login content, not on `body` itself — body exists
        # on the login page too, so a slow CI runner can grab the pre-submit
        # body before the form submit navigates and miss `Site administration`
        # entirely. Pipeline #300 ate this flake; locally the submit always
        # completes first. wait_for retries on AssertionError up to MAX_WAIT.
        self.wait_for(lambda: self.assertIn(
            "Site administration",
            self.browser.find_element(By.TAG_NAME, "body").text,
        ))
        body = self.browser.find_element(By.TAG_NAME, "body")
        self.assertIn("Users", body.text)
        self.assertIn("Tokens", body.text)
