/**
 * Seller Orders Management Test
 * 
 * Tags: @seller @p1 @orders
 * 
 * Tests seller order management functionality:
 * - View unprocessed orders
 * - View processed orders
 * - Process orders (mark as processed)
 * - View order details
 * - Export orders
 * - Filter and search orders
 */

import { test, expect } from '@playwright/test';
import { 
  printTestCase, 
  printSuccess, 
  printWarning, 
  ensureAuthenticated,
  waitForDataTable 
} from '../../helpers/test-helpers';

test.describe('06_Seller_Portal - Orders Management', () => {
  test.use({ storageState: 'auth.json' });
  
  test.beforeEach(async ({ page }) => {
    await ensureAuthenticated(page);
  });
  
  test('Test Case 1: Navigate to orders page', async ({ page }) => {
    printTestCase(1, 'Navigate to Orders Page');
    
    await page.goto('/seller/orders');
    await page.waitForLoadState('networkidle');
    
    // Verify orders page loaded
    const ordersHeader = page.locator('h6:has-text("Order Management"), h1:has-text("Orders"), .card-header:has-text("Order")');
    const headerVisible = await ordersHeader.first().isVisible({ timeout: 5000 }).catch(() => false);
    
    if (headerVisible) {
      printSuccess('Orders page loaded');
      
      // Verify tabs exist
      const tabs = page.locator('#ordersTab, .nav-tabs');
      if (await tabs.isVisible().catch(() => false)) {
        printSuccess('Order tabs visible');
      }
    } else {
      printWarning('Orders page header not found - may not have seller orders access');
    }
  });
  
  test('Test Case 2: View unprocessed orders tab', async ({ page }) => {
    printTestCase(2, 'View Unprocessed Orders Tab');
    
    await page.goto('/seller/orders');
    await page.waitForLoadState('networkidle');
    
    // Click unprocessed tab
    const unprocessedTab = page.locator('#unprocessed-tab, button:has-text("Unprocessed")');
    const tabVisible = await unprocessedTab.isVisible({ timeout: 5000 }).catch(() => false);
    
    if (!tabVisible) {
      printWarning('Unprocessed orders tab not found - may not have seller orders access');
      return;
    }
    
    await unprocessedTab.click();
    await page.waitForTimeout(1000);
    
    printSuccess('Unprocessed orders tab clicked');
    
    // Verify tab count badge
    const countBadge = page.locator('#unprocessed-count');
    if (await countBadge.isVisible().catch(() => false)) {
      const count = await countBadge.textContent();
      printSuccess(`Unprocessed orders count: ${count}`);
    }
    
    // Wait for DataTable to initialize
    await page.waitForFunction(() => {
      const table = document.querySelector('#unprocessedOrdersTable, table[id*="unprocessed"]');
      return table !== null;
    }, { timeout: 10000 }).catch(() => {});
    
    // Check for orders table
    const ordersTable = page.locator('#unprocessedOrdersTable, table[id*="unprocessed"]');
    if (await ordersTable.isVisible().catch(() => false)) {
      printSuccess('Unprocessed orders table visible');
      
      const orderRows = ordersTable.locator('tbody tr');
      const rowCount = await orderRows.count();
      
      if (rowCount > 0) {
        printSuccess(`Found ${rowCount} unprocessed order(s)`);
        
        // Verify table columns
        const headers = ordersTable.locator('thead th');
        const headerTexts: string[] = [];
        const headerCount = await headers.count();
        
        for (let i = 0; i < headerCount; i++) {
          const text = await headers.nth(i).textContent();
          if (text && text.trim()) {
            headerTexts.push(text.trim());
          }
        }
        printSuccess(`Table columns: ${headerTexts.join(', ')}`);
      } else {
        printSuccess('No unprocessed orders (empty state)');
      }
    } else {
      printWarning('Unprocessed orders table not found');
    }
  });
  
  test('Test Case 3: View processed orders tab', async ({ page }) => {
    printTestCase(3, 'View Processed Orders Tab');
    
    await page.goto('/seller/orders');
    await page.waitForLoadState('networkidle');
    
    // Click processed tab
    const processedTab = page.locator('#processed-tab, button:has-text("Processed")');
    const tabVisible = await processedTab.isVisible({ timeout: 5000 }).catch(() => false);
    
    if (!tabVisible) {
      printWarning('Processed orders tab not found - may not have seller orders access');
      return;
    }
    
    await processedTab.click();
    await page.waitForTimeout(1000);
    
    printSuccess('Processed orders tab clicked');
    
    // Verify tab count badge
    const countBadge = page.locator('#processed-count');
    if (await countBadge.isVisible().catch(() => false)) {
      const count = await countBadge.textContent();
      printSuccess(`Processed orders count: ${count}`);
    }
    
    // Wait for DataTable to initialize
    await page.waitForFunction(() => {
      const table = document.querySelector('#processedOrdersTable, table[id*="processed"]');
      return table !== null;
    }, { timeout: 10000 }).catch(() => {});
    
    // Check for orders table
    const ordersTable = page.locator('#processedOrdersTable, table[id*="processed"]');
    if (await ordersTable.isVisible().catch(() => false)) {
      printSuccess('Processed orders table visible');
      
      const orderRows = ordersTable.locator('tbody tr');
      const rowCount = await orderRows.count();
      
      if (rowCount > 0) {
        printSuccess(`Found ${rowCount} processed order(s)`);
      } else {
        printSuccess('No processed orders (empty state)');
      }
    } else {
      printWarning('Processed orders table not found');
    }
  });
  
  test('Test Case 4: Select orders for processing', async ({ page }) => {
    printTestCase(4, 'Select Orders for Processing');
    
    await page.goto('/seller/orders');
    await page.waitForLoadState('networkidle');
    
    // Ensure we're on unprocessed tab
    const unprocessedTab = page.locator('#unprocessed-tab, button:has-text("Unprocessed")');
    const tabVisible = await unprocessedTab.isVisible({ timeout: 5000 }).catch(() => false);
    
    if (!tabVisible) {
      printWarning('Unprocessed orders tab not found - may not have seller orders access');
      return;
    }
    
    await unprocessedTab.click();
    await page.waitForTimeout(1000);
    
    // Wait for table
    const ordersTable = page.locator('#unprocessedOrdersTable, table[id*="unprocessed"]');
    await page.waitForTimeout(2000);
    
    if (await ordersTable.isVisible().catch(() => false)) {
      const orderRows = ordersTable.locator('tbody tr');
      const rowCount = await orderRows.count();
      
      if (rowCount > 0) {
        printSuccess(`Found ${rowCount} order(s) to select`);
        
        // Try to select first order checkbox
        const firstCheckbox = orderRows.first().locator('input[type="checkbox"]');
        if (await firstCheckbox.isVisible().catch(() => false)) {
          await firstCheckbox.check();
          printSuccess('Selected first order');
          
          // Verify process button appears
          const processBtn = page.locator('button:has-text("Process"), button:has-text("Mark as Processed")');
          if (await processBtn.isVisible({ timeout: 2000 }).catch(() => false)) {
            printSuccess('Process button visible after selection');
          }
        } else {
          printWarning('Order checkboxes not found');
        }
      } else {
        printWarning('No unprocessed orders to select');
      }
    } else {
      printWarning('Orders table not visible');
    }
  });
  
  test('Test Case 5: Test select all orders', async ({ page }) => {
    printTestCase(5, 'Test Select All Orders');
    
    await page.goto('/seller/orders');
    await page.waitForLoadState('networkidle');
    
    // Ensure we're on unprocessed tab
    const unprocessedTab = page.locator('#unprocessed-tab, button:has-text("Unprocessed")');
    const tabVisible = await unprocessedTab.isVisible({ timeout: 5000 }).catch(() => false);
    
    if (!tabVisible) {
      printWarning('Unprocessed orders tab not found - may not have seller orders access');
      return;
    }
    
    await unprocessedTab.click();
    await page.waitForTimeout(2000);
    
    // Look for select all checkbox
    const selectAllCheckbox = page.locator('#selectAllUnprocessed, thead input[type="checkbox"]');
    if (await selectAllCheckbox.isVisible({ timeout: 2000 }).catch(() => false)) {
      await selectAllCheckbox.check();
      printSuccess('Select all checkbox checked');
      
      // Wait a moment for checkboxes to update
      await page.waitForTimeout(500);
      
      // Count selected checkboxes
      const selectedCheckboxes = page.locator('tbody input[type="checkbox"]:checked');
      const selectedCount = await selectedCheckboxes.count();
      
      if (selectedCount > 0) {
        printSuccess(`Selected ${selectedCount} order(s)`);
      }
    } else {
      printWarning('Select all checkbox not found');
    }
  });
  
  test('Test Case 6: View order details', async ({ page }) => {
    printTestCase(6, 'View Order Details');
    
    await page.goto('/seller/orders');
    await page.waitForLoadState('networkidle');
    
    // Wait for table
    await page.waitForTimeout(2000);
    
    const ordersTable = page.locator('#unprocessedOrdersTable, #processedOrdersTable, table[id*="orders"]').first();
    if (await ordersTable.isVisible().catch(() => false)) {
      const orderRows = ordersTable.locator('tbody tr');
      const rowCount = await orderRows.count();
      
      if (rowCount > 0) {
        // Look for view button or click row
        const viewBtn = orderRows.first().locator('button:has-text("View"), a:has-text("View"), .btn-view');
        if (await viewBtn.isVisible({ timeout: 2000 }).catch(() => false)) {
          await viewBtn.click();
          await page.waitForTimeout(1000);
          
          // Check for order details modal or page
          const orderDetails = page.locator('#orderDetailsModal, .modal:visible, [class*="order-detail"]');
          if (await orderDetails.isVisible({ timeout: 3000 }).catch(() => false)) {
            printSuccess('Order details view opened');
            
            // Close modal if present
            const closeBtn = page.locator('.modal .btn-close, .modal button:has-text("Close")');
            if (await closeBtn.isVisible().catch(() => false)) {
              await closeBtn.click();
            }
          } else {
            printWarning('Order details view not found');
          }
        } else {
          // Try clicking the row
          await orderRows.first().click();
          await page.waitForTimeout(1000);
          printWarning('No explicit view button - tried clicking row');
        }
      } else {
        printWarning('No orders available to view');
      }
    } else {
      printWarning('Orders table not visible');
    }
  });
  
  test('Test Case 7: Test order search', async ({ page }) => {
    printTestCase(7, 'Test Order Search');
    
    await page.goto('/seller/orders');
    await page.waitForLoadState('networkidle');
    
    await page.waitForTimeout(2000);
    
    // Look for search input
    const searchInput = page.locator('input[type="search"], input[placeholder*="Search"]');
    if (await searchInput.isVisible({ timeout: 2000 }).catch(() => false)) {
      printSuccess('Search input found');
      
      // Try searching
      await searchInput.fill('test');
      await page.waitForTimeout(1500);
      
      printSuccess('Search performed');
      
      // Clear search
      await searchInput.clear();
      await page.waitForTimeout(1000);
    } else {
      printWarning('Search input not found');
    }
  });
  
  test('Test Case 8: Test order export', async ({ page }) => {
    printTestCase(8, 'Test Order Export');
    
    await page.goto('/seller/orders');
    await page.waitForLoadState('networkidle');
    
    await page.waitForTimeout(2000);
    
    // Look for export button
    const exportBtn = page.locator('button:has-text("Export"), button:has-text("Excel"), button:has-text("PDF")');
    if (await exportBtn.first().isVisible({ timeout: 2000 }).catch(() => false)) {
      printSuccess('Export button found');
      
      // Note: We won't actually trigger the download in tests
      const exportText = await exportBtn.first().textContent();
      printSuccess(`Export option available: ${exportText}`);
    } else {
      printWarning('Export button not found');
    }
  });
  
  test('Test Case 9: Test order filtering', async ({ page }) => {
    printTestCase(9, 'Test Order Filtering');
    
    await page.goto('/seller/orders');
    await page.waitForLoadState('networkidle');
    
    await page.waitForTimeout(2000);
    
    // Look for filter options
    const filterSelects = page.locator('select[id*="filter"], .filter-select');
    const filterCount = await filterSelects.count();
    
    if (filterCount > 0) {
      printSuccess(`Found ${filterCount} filter option(s)`);
      
      // Try using first filter
      const firstFilter = filterSelects.first();
      const options = firstFilter.locator('option');
      const optionCount = await options.count();
      
      if (optionCount > 1) {
        await firstFilter.selectOption({ index: 1 });
        await page.waitForTimeout(1500);
        printSuccess('Filter applied');
      }
    } else {
      printWarning('No filter options found');
    }
  });
  
  test('Test Case 10: Verify order table pagination', async ({ page }) => {
    printTestCase(10, 'Verify Order Table Pagination');
    
    await page.goto('/seller/orders');
    await page.waitForLoadState('networkidle');
    
    await page.waitForTimeout(2000);
    
    // Look for pagination controls
    const pagination = page.locator('.dataTables_paginate, .pagination, [class*="paging"]');
    if (await pagination.isVisible({ timeout: 2000 }).catch(() => false)) {
      printSuccess('Pagination controls found');
      
      // Check for next button
      const nextBtn = pagination.locator('a:has-text("Next"), button:has-text("Next"), .next');
      if (await nextBtn.isVisible().catch(() => false)) {
        const isDisabled = await nextBtn.getAttribute('class').then(c => c?.includes('disabled'));
        if (!isDisabled) {
          printSuccess('Pagination active (multiple pages)');
        } else {
          printSuccess('Pagination present (single page)');
        }
      }
    } else {
      printWarning('Pagination not found - may be using scrolling');
    }
  });
});

