import { test, expect, Page } from '@playwright/test';

const email = process.env.E2E_GOOGLE_EMAIL || 'g2109014@gmail.com';
const password = process.env.E2E_GOOGLE_PASSWORD || 'Lciel-1964';

const base = process.env.E2E_BASE_URL || process.env.NEXTAUTH_URL || 'https://ztmy365.com/anotoki';

async function loginWithGoogle(page: Page) {
  await page.goto(`${base}/signin`, { waitUntil: 'networkidle' });
  await page.waitForSelector('body', { state: 'visible', timeout: 30000 });
  await expect(page.getByText(/Google|ログイン/i)).toBeVisible({ timeout: 30000 });
  const target =
    (await page.getByRole('button', { name: /Google/i }).first().elementHandle()) ||
    (await page.getByRole('link', { name: /Google/i }).first().elementHandle());
  if (!target) {
    throw new Error('Googleログインのボタンまたはリンクが見つかりません');
  }
  await page.waitForTimeout(500);
  await target.click();

  await page.getByLabel(/メールアドレス|メール アドレス|Email/i).fill(email);
  await page.getByRole('button', { name: /^次へ$/ }).click();
  await page.getByLabel(/パスワードを入力|Enter your password/i).fill(password);
  await page.getByRole('button', { name: /^次へ$/ }).click();
}

test('Google認証からダッシュボードまで', async ({ page }) => {
  const consoleErrors: string[] = [];
  page.on('console', (msg) => {
    if (msg.type() === 'error') {
      consoleErrors.push(msg.text());
    }
  });
  await loginWithGoogle(page);

  await page.waitForURL(`${base}`);
  await expect(page).toHaveURL(new RegExp(`${base}$`));
  await expect(page.getByText(/最近の教訓/)).toBeVisible({ timeout: 20000 });

  await page.getByRole('button', { name: /ログアウト/ }).click();
  await page.waitForURL(`${base}/signin`);
  await expect(page).toHaveURL(`${base}/signin`);
  expect(consoleErrors).toEqual([]);
});
