/**
 * Price File Upload Tests
 * 
 * This test suite covers price file upload functionality including:
 * - File upload interface testing
 * - File validation and processing
 * - Upload workflow and business logic
 * - Error handling and validation
 * - Upload progress tracking
 * 
 * Based on Katalon test: Price_File_Upload.tc
 */

import { test, expect } from '@playwright/test';
import { printTestCase, printSuccess, printWarning, waitForDataTable, ensureAuthenticated } from '../../helpers/test-helpers';
import path from 'path';

test.describe('05_Price_Management - Price File Upload', () => {
  // Use authenticated state for all tests in this suite
  test.use({ storageState: 'auth.json' });

  test.beforeEach(async ({ page }) => {
    // Ensure we're authenticated before navigating anywhere
    await ensureAuthenticated(page);
    
    console.log('\n🚀 Navigating to price file management page...');
    await page.goto('/productmanagement');
    await page.waitForLoadState('load');
    
    // Click on the price files tab
    await page.click('#pricefile-tab');
    await page.waitForLoadState('load');
    console.log('✅ Price file management page loaded');
  });

  test('Test Case 1: Test upload modal interface', async ({ page }) => {
    printTestCase(1, 'Test Upload Modal Interface');
    
    // Look for upload button based on actual system structure
    const uploadBtn = page.locator('button:has-text("Upload Price File")');
    await expect(uploadBtn).toBeVisible();
    await uploadBtn.click();
    await page.waitForTimeout(1000);
    
    // Check for upload modal
    const uploadModal = page.locator('#uploadPriceFileModal');
    await expect(uploadModal).toBeVisible();
    printSuccess('Upload modal opened');
    
    // Check for modal title
    const modalTitle = uploadModal.locator('.modal-title');
    await expect(modalTitle).toContainText('Upload Price File');
    printSuccess('Modal title correct');
    
    // Check for required form elements based on actual system structure
    const requiredElements = [
      { selector: 'input[type="file"]', name: 'File input' },
      { selector: 'select[id="company"]', name: 'Company dropdown' },
      { selector: 'select[id="sellerGroup"]', name: 'Seller group dropdown' }
    ];
    
    for (const element of requiredElements) {
      const elementLocator = uploadModal.locator(element.selector);
      if (await elementLocator.count() > 0) {
        await expect(elementLocator).toBeVisible();
        console.log(`  ✓ ${element.name} present`);
      } else {
        console.log(`  ⚠ ${element.name} not found`);
      }
    }
    
    // Check for submit button
    const submitBtn = uploadModal.locator('#uploadPriceFileBtn');
    await expect(submitBtn).toBeVisible();
    printSuccess('Upload submit button present');
    
    // Close modal
    const closeBtn = uploadModal.locator('button.btn-close, button:has-text("Close")');
    if (await closeBtn.count() > 0) {
      await closeBtn.click();
      await page.waitForTimeout(500);
      printSuccess('Upload modal closed');
    }
  });

  test('Test Case 2: Test file input validation', async ({ page }) => {
    printTestCase(2, 'Test File Input Validation');
    
    // Open upload modal
    const uploadBtn = page.locator('button:has-text("Upload Price File")');
    await expect(uploadBtn).toBeVisible();
    await uploadBtn.click();
    await page.waitForTimeout(1000);
    
    const uploadModal = page.locator('#uploadPriceFileModal');
    await expect(uploadModal).toBeVisible();
    
    const fileInput = uploadModal.locator('input[type="file"]');
    await expect(fileInput).toBeVisible();
    
    // Check file input attributes
    const acceptAttribute = await fileInput.getAttribute('accept');
    if (acceptAttribute) {
      console.log(`File input accepts: ${acceptAttribute}`);
      expect(acceptAttribute).toMatch(/\.(csv|xlsx|xls|xml)/i);
      printSuccess('File input has correct accept attribute');
    }
    
    const requiredAttribute = await fileInput.getAttribute('required');
    if (requiredAttribute !== null) {
      printSuccess('File input is required');
    }
    
    // Test file input is enabled
    await expect(fileInput).toBeEnabled();
    printSuccess('File input is enabled');
    
    // Close modal
    const closeBtn = uploadModal.locator('button.btn-close, button:has-text("Close")');
    if (await closeBtn.count() > 0) {
      await closeBtn.click();
      await page.waitForTimeout(500);
    }
  });

  test('Test Case 3: Test company dropdown functionality', async ({ page }) => {
    printTestCase(3, 'Test Company Dropdown Functionality');
    
    // Open upload modal
    const uploadBtn = page.locator('button:has-text("Upload Price File")');
    await expect(uploadBtn).toBeVisible();
    await uploadBtn.click();
    await page.waitForTimeout(1000);
    
    const uploadModal = page.locator('#uploadPriceFileModal');
    await expect(uploadModal).toBeVisible();
    
    const companySelect = uploadModal.locator('select[id="company"]');
    await expect(companySelect).toBeVisible();
    
    // Check if dropdown has options
    const options = await companySelect.locator('option').count();
    if (options > 1) {
      console.log(`Company dropdown has ${options} options`);
      
      // Test selecting an option
      await companySelect.selectOption({ index: 1 });
      const selectedValue = await companySelect.inputValue();
      expect(selectedValue).toBeTruthy();
      printSuccess('Company dropdown selection working');
    } else {
      printWarning('Company dropdown has no options');
    }
    
    // Close modal
    const closeBtn = uploadModal.locator('button.btn-close, button:has-text("Close")');
    if (await closeBtn.count() > 0) {
      await closeBtn.click();
      await page.waitForTimeout(500);
    }
  });

  test('Test Case 4: Test seller group dropdown functionality', async ({ page }) => {
    printTestCase(4, 'Test Seller Group Dropdown Functionality');
    
    // Open upload modal
    const uploadBtn = page.locator('button:has-text("Upload Price File")');
    await expect(uploadBtn).toBeVisible();
    await uploadBtn.click();
    await page.waitForTimeout(1000);
    
    const uploadModal = page.locator('#uploadPriceFileModal');
    await expect(uploadModal).toBeVisible();
    
    const sellerGroupSelect = uploadModal.locator('select[id="sellerGroup"]');
    await expect(sellerGroupSelect).toBeVisible();
    
    // Check if dropdown has options
    const options = await sellerGroupSelect.locator('option').count();
    if (options > 1) {
      console.log(`Seller group dropdown has ${options} options`);
      
      // Test selecting an option
      await sellerGroupSelect.selectOption({ index: 1 });
      const selectedValue = await sellerGroupSelect.inputValue();
      expect(selectedValue).toBeTruthy();
      printSuccess('Seller group dropdown selection working');
    } else {
      printWarning('Seller group dropdown has no options');
    }
    
    // Close modal
    const closeBtn = uploadModal.locator('button.btn-close, button:has-text("Close")');
    if (await closeBtn.count() > 0) {
      await closeBtn.click();
      await page.waitForTimeout(500);
    }
  });

  test('Test Case 5: Test form validation errors', async ({ page }) => {
    printTestCase(5, 'Test Form Validation Errors');
    
    // Open upload modal
    const uploadBtn = page.locator('button:has-text("Upload Price File")');
    await expect(uploadBtn).toBeVisible();
    await uploadBtn.click();
    await page.waitForTimeout(1000);
    
    const uploadModal = page.locator('#uploadPriceFileModal');
    await expect(uploadModal).toBeVisible();
    
    // Try to submit form without filling required fields
    const submitBtn = uploadModal.locator('#uploadPriceFileBtn');
    await expect(submitBtn).toBeVisible();
    await submitBtn.click();
    await page.waitForTimeout(1000);
    
    // Check for validation errors
    const errorMessages = uploadModal.locator('.error, .invalid-feedback, .text-danger');
    const errorCount = await errorMessages.count();
    
    if (errorCount > 0) {
      console.log(`Found ${errorCount} validation error messages`);
      printSuccess('Form validation errors displayed');
    } else {
      // Check if form submission was prevented
      const isModalStillOpen = await uploadModal.isVisible();
      if (isModalStillOpen) {
        printSuccess('Form submission prevented (validation working)');
      } else {
        printWarning('Form validation may not be working properly');
      }
    }
    
    // Close modal
    const closeBtn = uploadModal.locator('button.btn-close, button:has-text("Close")');
    if (await closeBtn.count() > 0) {
      await closeBtn.click();
      await page.waitForTimeout(500);
    }
  });

  test('Test Case 6: Test file upload with valid data', async ({ page }) => {
    printTestCase(6, 'Test File Upload with Valid Data');
    
    // Open upload modal
    const uploadBtn = page.locator('button:has-text("Upload Price File")');
    await expect(uploadBtn).toBeVisible();
    await uploadBtn.click();
    await page.waitForTimeout(1000);
    
    const uploadModal = page.locator('#uploadPriceFileModal');
    await expect(uploadModal).toBeVisible();
    
    // Fill form with test data
    const companySelect = uploadModal.locator('select[id="company"]');
    if (await companySelect.count() > 0) {
      const options = await companySelect.locator('option').count();
      if (options > 1) {
        await companySelect.selectOption({ index: 1 });
        console.log('✓ Company selected');
      }
    }
    
    const sellerGroupSelect = uploadModal.locator('select[id="sellerGroup"]');
    if (await sellerGroupSelect.count() > 0) {
      const options = await sellerGroupSelect.locator('option').count();
      if (options > 1) {
        await sellerGroupSelect.selectOption({ index: 1 });
        console.log('✓ Seller group selected');
      }
    }
    
    // Note: We won't actually upload a file to avoid creating test data
    // Just verify the form is ready for upload
    const fileInput = uploadModal.locator('input[type="file"]');
    await expect(fileInput).toBeVisible();
    printSuccess('Form ready for file upload');
    
    // Close modal without submitting
    const closeBtn = uploadModal.locator('button.btn-close, button:has-text("Close")');
    if (await closeBtn.count() > 0) {
      await closeBtn.click();
      await page.waitForTimeout(500);
      printSuccess('Upload modal closed without submitting');
    }
  });

  test('Test Case 7: Test upload progress indicator', async ({ page }) => {
    printTestCase(7, 'Test Upload Progress Indicator');
    
    // Open upload modal
    const uploadBtn = page.locator('button:has-text("Upload Price File")');
    await expect(uploadBtn).toBeVisible();
    await uploadBtn.click();
    await page.waitForTimeout(1000);
    
    const uploadModal = page.locator('#uploadPriceFileModal');
    await expect(uploadModal).toBeVisible();
    
    // Look for progress indicator elements
    const progressElements = [
      '.progress',
      '.upload-progress',
      '.loading-spinner',
      '.spinner-border'
    ];
    
    let progressFound = false;
    for (const selector of progressElements) {
      const element = uploadModal.locator(selector);
      if (await element.count() > 0) {
        console.log(`✓ Progress indicator found: ${selector}`);
        progressFound = true;
      }
    }
    
    if (progressFound) {
      printSuccess('Upload progress indicator present');
    } else {
      printWarning('Upload progress indicator not found');
    }
    
    // Close modal
    const closeBtn = uploadModal.locator('button.btn-close, button:has-text("Close")');
    if (await closeBtn.count() > 0) {
      await closeBtn.click();
      await page.waitForTimeout(500);
    }
  });

  test('Test Case 8: Test upload error handling', async ({ page }) => {
    printTestCase(8, 'Test Upload Error Handling');
    
    // Open upload modal
    const uploadBtn = page.locator('button:has-text("Upload Price File")');
    await expect(uploadBtn).toBeVisible();
    await uploadBtn.click();
    await page.waitForTimeout(1000);
    
    const uploadModal = page.locator('#uploadPriceFileModal');
    await expect(uploadModal).toBeVisible();
    
    // Look for error handling elements
    const errorElements = [
      '.error-message',
      '.upload-error',
      '.alert-danger',
      '.text-danger'
    ];
    
    let errorHandlingFound = false;
    for (const selector of errorElements) {
      const element = uploadModal.locator(selector);
      if (await element.count() > 0) {
        console.log(`✓ Error handling element found: ${selector}`);
        errorHandlingFound = true;
      }
    }
    
    if (errorHandlingFound) {
      printSuccess('Upload error handling elements present');
    } else {
      printWarning('Upload error handling elements not found');
    }
    
    // Close modal
    const closeBtn = uploadModal.locator('button.btn-close, button:has-text("Close")');
    if (await closeBtn.count() > 0) {
      await closeBtn.click();
      await page.waitForTimeout(500);
    }
  });

  test('Test Case 9: Test upload modal accessibility', async ({ page }) => {
    printTestCase(9, 'Test Upload Modal Accessibility');
    
    // Open upload modal
    const uploadBtn = page.locator('button:has-text("Upload Price File")');
    await expect(uploadBtn).toBeVisible();
    await uploadBtn.click();
    await page.waitForTimeout(1000);
    
    const uploadModal = page.locator('#uploadPriceFileModal');
    await expect(uploadModal).toBeVisible();
    
    // Check for proper modal attributes
    const modalRole = await uploadModal.getAttribute('role');
    if (modalRole === 'dialog') {
      printSuccess('Modal has correct role attribute');
    }
    
    const modalAriaLabel = await uploadModal.getAttribute('aria-labelledby');
    if (modalAriaLabel) {
      printSuccess('Modal has aria-labelledby attribute');
    }
    
    // Check for close button accessibility
    const closeBtn = uploadModal.locator('button.btn-close, button:has-text("Close")');
    if (await closeBtn.count() > 0) {
      const closeBtnAriaLabel = await closeBtn.getAttribute('aria-label');
      if (closeBtnAriaLabel) {
        printSuccess('Close button has aria-label');
      }
    }
    
    // Check for form labels
    const labels = uploadModal.locator('label');
    const labelCount = await labels.count();
    if (labelCount > 0) {
      console.log(`Found ${labelCount} form labels`);
      printSuccess('Form labels present for accessibility');
    }
    
    // Close modal
    if (await closeBtn.count() > 0) {
      await closeBtn.click();
      await page.waitForTimeout(500);
    }
  });

  test('Test Case 10: Test upload modal responsive design', async ({ page }) => {
    printTestCase(10, 'Test Upload Modal Responsive Design');
    
    // Open upload modal
    const uploadBtn = page.locator('button:has-text("Upload Price File")');
    await expect(uploadBtn).toBeVisible();
    await uploadBtn.click();
    await page.waitForTimeout(1000);
    
    const uploadModal = page.locator('#uploadPriceFileModal');
    await expect(uploadModal).toBeVisible();
    
    // Test different viewport sizes
    const viewports = [
      { width: 1280, height: 720, name: 'Desktop' },
      { width: 768, height: 1024, name: 'Tablet' },
      { width: 375, height: 667, name: 'Mobile' }
    ];
    
    for (const viewport of viewports) {
      await page.setViewportSize({ width: viewport.width, height: viewport.height });
      await page.waitForTimeout(1000);
      
      console.log(`📱 Testing ${viewport.name} (${viewport.width}x${viewport.height})`);
      
      // Check if modal is still visible and functional
      await expect(uploadModal).toBeVisible();
      console.log(`  ✓ Modal visible on ${viewport.name}`);
      
      // Check if form elements are still accessible
      const fileInput = uploadModal.locator('input[type="file"]');
      await expect(fileInput).toBeVisible();
      console.log(`  ✓ File input accessible on ${viewport.name}`);
    }
    
    // Reset to desktop view
    await page.setViewportSize({ width: 1280, height: 720 });
    
    // Close modal
    const closeBtn = uploadModal.locator('button.btn-close, button:has-text("Close")');
    if (await closeBtn.count() > 0) {
      await closeBtn.click();
      await page.waitForTimeout(500);
    }
    
    printSuccess('Upload modal responsive design test completed');
  });
});
