import { test, expect } from '@playwright/test';
import { siteConfig } from '../../config/siteConfig';
import { loginViaUI, registerAccount, isLoggedIn } from '../../support/auth-helpers';
import { waitForHydration } from '../../support/cart-helpers';

test.describe('Authentication', () => {
    test.describe('Login', () => {
        test('can login with valid credentials', async ({ page }) => {
            const email = siteConfig.auth.testEmail;
            const password = siteConfig.auth.testPassword;

            test.skip(
                !email || !password,
                'E2E_TEST_EMAIL and E2E_TEST_PASSWORD are required for login tests'
            );

            const success = await loginViaUI(page, email!, password!);

            expect(success, 'User should be logged in after valid login').toBeTruthy();
        });

        test('shows error for invalid credentials', async ({ page }) => {
            const success = await loginViaUI(
                page,
                'invalid-e2e-test@fake.matsuyaginza.com',
                'WrongPassword123!'
            );

            // Should NOT be logged in
            expect(
                success,
                'Invalid credentials should not result in successful login'
            ).toBeFalsy();

            // Verify we're still on the login page
            const stillOnLogin =
                page.url().includes('sign-in') || page.url().includes('login');
            expect(
                stillOnLogin,
                'Should remain on login page after failed login attempt'
            ).toBeTruthy();
        });
    });

    test.describe('Registration', () => {
        test('can register a new account', async ({ page }) => {
            const timestamp = Date.now();
            const testEmail = `e2e-test-${timestamp}@test.matsuyaginza.com`;

            const success = await registerAccount(page, {
                familyName: 'Test',
                firstName: 'Taro',
                email: testEmail,
                password: 'E2eTest123!',
            });

            expect(
                success,
                'New account registration should succeed'
            ).toBeTruthy();

            // Verify we can detect logged-in state
            const loggedIn = await isLoggedIn(page);
            expect(
                loggedIn,
                'User should be automatically logged in after registration'
            ).toBeTruthy();
        });
    });
});
