import { initDriver, getDriver, quitDriver } from "../helpers/driver";
import { TestIDs } from "../helpers/selectors";
import {
  waitForTestId,
  ensureOnLoginScreen,
  performLogin,
} from "../helpers/utils";

describe("Login", () => {
  beforeAll(async () => {
    await initDriver();
    const driver = getDriver();

    // Dismiss Expo Go banner by tapping near the top of the screen
    await driver.pause(3000);
    const { width } = await driver.getWindowSize();
    await driver.touchAction({ action: "tap", x: Math.round(width / 2), y: 100 });
    await driver.pause(500);
  });

  beforeEach(async () => {
    const driver = getDriver();
    await ensureOnLoginScreen(driver);
  });

  it("should show error when fields are empty", async () => {
    const driver = getDriver();

    // Tap login without entering credentials
    const loginButton = await waitForTestId(driver, TestIDs.LOGIN_BUTTON);
    await loginButton.click();

    // Error message should appear
    const errorText = await waitForTestId(driver, TestIDs.LOGIN_ERROR_TEXT);
    const text = await errorText.getText();
    expect(text).toContain("Bitte alle Felder");
  });

  it("should show error for invalid credentials", async () => {
    const driver = getDriver();

    await performLogin(driver, "invalid_user", "wrong_password");

    // Wait for error message
    const errorText = await waitForTestId(
      driver,
      TestIDs.LOGIN_ERROR_TEXT,
      30_000,
    );
    const text = await errorText.getText();
    expect(text).toContain("Anmeldung fehlgeschlagen");
  });

  it("should login successfully with valid credentials", async () => {
    const driver = getDriver();
    const testUser = process.env.TEST_USER || "test";
    const testPassword = process.env.TEST_PASSWORD || "test";

    await performLogin(driver, testUser, testPassword);

    // Chat screen should appear after successful login
    const chatInput = await waitForTestId(
      driver,
      TestIDs.CHAT_MESSAGE_INPUT,
      30_000,
    );
    expect(await chatInput.isDisplayed()).toBe(true);
  });

  afterAll(async () => {
    await quitDriver();
  });
});
