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

test.describe('Cloud Storage Path Resolution E2E', () => {
    test.beforeEach(async ({ page }) => {
        // Navigate to the file management index
        await page.goto('/tenant/file');
        await expect(page).toHaveURL(/file/);
    });

    test('should allow typing a new path and show datalist suggestions', async ({ page }) => {
        const pathInput = page.locator('#path');
        
        // 1. Verify existence of the integrated destination input
        await expect(pathInput).toBeVisible();
        await expect(pathInput).toHaveAttribute('list', 'folderList');

        // 2. Type a path
        await pathInput.fill('E2E_Test_Folder');
        
        // 3. Trigger folder loading if not already loaded (via refresh button)
        const refreshBtn = page.locator('button[title*="Refresh"]');
        await refreshBtn.click();
        
        // 4. Verify that the datalist exists (Browser internals check)
        const datalist = page.locator('#folderList');
        await expect(datalist).toBeAttached();
    });

    test('should reject relative path segments (AC-6)', async ({ page }) => {
        const pathInput = page.locator('#path');
        const fileInput = page.locator('input[type="file"]');
        const submitBtn = page.locator('button:has-text("Upload File")');

        // 1. Fill invalid path
        await pathInput.fill('../illegal_path');

        // 2. Select a dummy file (Playwright handles this via setInputFiles)
        // Note: In a real E2E run, we would provide a small buffer/file
        // await fileInput.setInputFiles({
        //     name: 'test.txt',
        //     mimeType: 'text/plain',
        //     buffer: Buffer.from('this is a test')
        // });

        // 3. Attempt upload
        await submitBtn.click();

        // 4. Verify error message for Forbidden segments (FR-1 / AC-6)
        // The error should appear in the progressText or a toast
        const errorText = page.locator('#progressText');
        await expect(errorText).toContainText(/relative segments/i);
    });

    test('should refresh the MediaTable after a successful upload', async ({ page }) => {
        // This test verifies the Livewire 3 event dispatching
        // 1. Perform a mock upload (or wait for one)
        // 2. Check if the table component receives the refresh
        
        const mediaTable = page.locator('.media-table-container'); // Assuming a class or ID
        await expect(mediaTable).toBeVisible();
        
        // In a real Playwright test, we would listen for the 'refreshMediaTable' event
        // or verify that a new row appears in the table.
    });
});
