const { test, expect } = require('@playwright/test');

test.describe('AutoBackups - Application Health Tests', () => {
  test('should check if the Flask application is running', async ({ page }) => {
    const response = await page.goto('/');
    
    // Just check that we get some response from the server
    expect(response.status()).toBeLessThan(500);
    
    const title = await page.title();
    console.log(`Application title: "${title}"`);
    
    // Check if the page has some content
    const bodyText = await page.textContent('body');
    expect(bodyText.length).toBeGreaterThan(10);
    
    await page.screenshot({ path: 'test-results/health-check.png' });
  });

  test('should check application endpoints availability', async ({ page }) => {
    const endpoints = ['/', '/config'];
    const results = {};
    
    for (const endpoint of endpoints) {
      try {
        const response = await page.goto(endpoint);
        results[endpoint] = {
          status: response.status(),
          accessible: response.status() < 500
        };
        console.log(`${endpoint}: Status ${response.status()}`);
      } catch (error) {
        results[endpoint] = {
          status: 'error',
          accessible: false,
          error: error.message
        };
        console.log(`${endpoint}: Error - ${error.message}`);
      }
    }
    
    // At least the root endpoint should be accessible
    expect(results['/'].accessible).toBe(true);
    
    console.log('Endpoint accessibility results:', results);
  });

  test('should check if static assets are loading', async ({ page }) => {
    await page.goto('/');
    
    // Check for common static assets
    const cssRequests = [];
    const jsRequests = [];
    
    page.on('response', response => {
      const url = response.url();
      if (url.includes('.css')) {
        cssRequests.push({ url, status: response.status() });
      } else if (url.includes('.js')) {
        jsRequests.push({ url, status: response.status() });
      }
    });
    
    // Wait a bit for assets to load
    await page.waitForTimeout(2000);
    
    console.log(`CSS requests: ${cssRequests.length}`);
    console.log(`JS requests: ${jsRequests.length}`);
    
    // Log any failed asset requests
    const failedAssets = [...cssRequests, ...jsRequests].filter(req => req.status >= 400);
    if (failedAssets.length > 0) {
      console.log('Failed asset requests:', failedAssets);
    }
  });
});
