/**
 * Seed the Stuff Balls E2E Test Suite
 * 
 * Creates the comprehensive 50-test suite for the autonomous e-commerce system.
 */

import { NextResponse } from 'next/server';
import { prisma } from '@/lib/db';

export const dynamic = 'force-dynamic';

const STUFF_BALLS_TEST_CASES = [
  { id: 'E2E-001', scenario: 'Customer places single standard stuff ball order, pays with credit card', objective: 'Validate happy path – standard order flow', expectedOutcome: 'Order confirmed → manufactured → packaged → shipped → delivered → payment settles in bank', priority: 'critical', category: 'happy_path' },
  { id: 'E2E-002', scenario: 'Order of 5 identical stuff balls, PayPal payment', objective: 'Multi-item order handling & batch processing', expectedOutcome: 'All items produced together, single shipment, funds in bank', priority: 'high', category: 'happy_path' },
  { id: 'E2E-003', scenario: 'Custom color selection stuff ball, debit card payment', objective: 'Custom configuration & manufacturing', expectedOutcome: 'Correct custom item produced, delivered, funds received', priority: 'high', category: 'happy_path' },
  { id: 'E2E-004', scenario: 'Order with gift wrapping add-on, Apple Pay', objective: 'Add-on services & alternate payment method', expectedOutcome: 'Item wrapped correctly, delivered, payment processed', priority: 'medium', category: 'happy_path' },
  { id: 'E2E-005', scenario: 'B2B bulk order (100 units), invoice / bank transfer payment', objective: 'High-volume B2B flow & non-card payment', expectedOutcome: 'Batch produced, bulk shipped, full payment received', priority: 'high', category: 'integration' },
  { id: 'E2E-006', scenario: 'Minimum quantity order (1 unit, no options)', objective: 'Base-case / minimal order validation', expectedOutcome: 'Processed normally to bank deposit', priority: 'critical', category: 'happy_path' },
  { id: 'E2E-007', scenario: 'Maximum allowed quantity order (e.g. 1,000 units)', objective: 'System capacity & large order splitting', expectedOutcome: 'Order accepted, produced (possibly in batches), delivered, full payment', priority: 'high', category: 'edge_case' },
  { id: 'E2E-008', scenario: 'Invalid order – zero quantity', objective: 'Input validation & early rejection', expectedOutcome: 'Rejected before payment processing – no cash movement', priority: 'critical', category: 'error_handling' },
  { id: 'E2E-009', scenario: 'Incomplete / invalid shipping address', objective: 'Address validation & correction workflow', expectedOutcome: 'Flagged → corrected → processed to delivery & bank', priority: 'high', category: 'error_handling' },
  { id: 'E2E-010', scenario: 'Initial payment declined, successful retry', objective: 'Payment retry & resilience', expectedOutcome: 'Order continues after successful retry → full delivery & settlement', priority: 'critical', category: 'error_handling' },
  { id: 'E2E-011', scenario: 'International order + international card + currency conversion', objective: 'Cross-border order & FX handling', expectedOutcome: 'Produced on-site, shipped internationally, funds converted & deposited', priority: 'high', category: 'integration' },
  { id: 'E2E-012', scenario: 'First recurring subscription order', objective: 'Subscription creation & initial fulfillment', expectedOutcome: 'Recurring profile created, first item delivered, payment in bank', priority: 'high', category: 'happy_path' },
  { id: 'E2E-013', scenario: 'Valid promo / discount code applied', objective: 'Promotion engine & reduced payment', expectedOutcome: 'Discount applied correctly, delivered, reduced amount in bank', priority: 'medium', category: 'happy_path' },
  { id: 'E2E-014', scenario: 'Expired promo code submitted', objective: 'Promotion expiration handling', expectedOutcome: 'Discount rejected, full price charged, order completes normally', priority: 'medium', category: 'error_handling' },
  { id: 'E2E-015', scenario: 'Order placed during peak / high queue volume', objective: 'Queueing, throttling & priority handling', expectedOutcome: 'Order queued → eventually processed → delivered → payment released', priority: 'high', category: 'edge_case' },
  { id: 'E2E-016', scenario: 'Low / out-of-stock raw material detected during order', objective: 'Auto-replenishment & production delay handling', expectedOutcome: 'Material reordered → delay → production resumes → delivery & bank', priority: 'high', category: 'edge_case' },
  { id: 'E2E-017', scenario: 'Quality inspection failure on produced item', objective: 'Quality control loop & rework', expectedOutcome: 'Failed item remanufactured → correct item shipped → delivered', priority: 'critical', category: 'integration' },
  { id: 'E2E-018', scenario: 'Local pickup instead of shipping', objective: 'Alternative fulfillment channel', expectedOutcome: 'Produced → notification sent → picked up → payment in bank', priority: 'medium', category: 'happy_path' },
  { id: 'E2E-019', scenario: 'Express / priority shipping selected', objective: 'Service level differentiation & queue jumping', expectedOutcome: 'Prioritized production → expedited shipping → fast delivery', priority: 'medium', category: 'happy_path' },
  { id: 'E2E-020', scenario: 'Carrier delay after label creation', objective: 'External dependency & customer communication', expectedOutcome: 'Tracked → notified → eventually delivered → payment already settled', priority: 'medium', category: 'integration' },
  { id: 'E2E-021', scenario: 'Cancellation before manufacturing begins', objective: 'Pre-production refund', expectedOutcome: 'Full refund issued, no production, net zero cash impact', priority: 'critical', category: 'error_handling' },
  { id: 'E2E-022', scenario: 'Cancellation after manufacturing but before shipping', objective: 'Post-production partial refund & restock', expectedOutcome: 'Partial refund, item restocked, adjusted funds in bank', priority: 'high', category: 'error_handling' },
  { id: 'E2E-023', scenario: 'Order with add-on accessories', objective: 'Bundling & multi-SKU fulfillment', expectedOutcome: 'All items produced/packaged together → delivered', priority: 'medium', category: 'happy_path' },
  { id: 'E2E-024', scenario: 'Expired card on file → switch to new valid card', objective: 'Payment method update during checkout', expectedOutcome: 'Successful payment → full order completion', priority: 'high', category: 'error_handling' },
  { id: 'E2E-025', scenario: 'Brief system outage after payment authorization', objective: 'Order recovery & state persistence', expectedOutcome: 'Order resumes → manufactured → delivered → bank', priority: 'critical', category: 'edge_case' },
  { id: 'E2E-026', scenario: 'Duplicate order submission (double-click / refresh)', objective: 'Idempotency & duplicate prevention', expectedOutcome: 'Only one order processed → delivered', priority: 'critical', category: 'edge_case' },
  { id: 'E2E-027', scenario: 'B2B purchase order (PO) based order', objective: 'Invoice-based payment & enterprise flow', expectedOutcome: 'Produced → shipped → payment received via invoice', priority: 'medium', category: 'integration' },
  { id: 'E2E-028', scenario: 'Seasonal / holiday-themed customization', objective: 'Time-bound / special material handling', expectedOutcome: 'Correct theme produced → delivered', priority: 'low', category: 'edge_case' },
  { id: 'E2E-029', scenario: 'Special characters / Unicode in name or address', objective: 'Internationalization & encoding', expectedOutcome: 'Correctly processed through entire flow', priority: 'medium', category: 'edge_case' },
  { id: 'E2E-030', scenario: 'High-value order requiring risk / fraud review', objective: 'Fraud / risk engine integration', expectedOutcome: 'Auto-cleared → produced → delivered', priority: 'high', category: 'integration' },
  { id: 'E2E-031', scenario: 'Installment / split payment order (if supported)', objective: 'Partial payment & staged fulfillment', expectedOutcome: 'Manufacturing starts on first payment, completes on final', priority: 'medium', category: 'integration' },
  { id: 'E2E-032', scenario: 'Order placed via referral / affiliate link', objective: 'Attribution & referral discount', expectedOutcome: 'Discount applied → delivered', priority: 'low', category: 'integration' },
  { id: 'E2E-033', scenario: 'Order placed during scheduled maintenance window', objective: 'Maintenance queuing & post-maintenance processing', expectedOutcome: 'Queued → processed after window → completed', priority: 'medium', category: 'edge_case' },
  { id: 'E2E-034', scenario: 'Manufacturing robot / line failure → failover to backup', objective: 'Production resilience & redundancy', expectedOutcome: 'Backup line completes order → delivered', priority: 'critical', category: 'edge_case' },
  { id: 'E2E-035', scenario: 'Shipping label contains data error (e.g. typo from input)', objective: 'Label correction & reprint', expectedOutcome: 'Auto-corrected or flagged → correct delivery', priority: 'medium', category: 'error_handling' },
  { id: 'E2E-036', scenario: 'Eco-friendly / sustainable packaging selected', objective: 'Optional packaging variants', expectedOutcome: 'Green packaging used → delivered', priority: 'low', category: 'happy_path' },
  { id: 'E2E-037', scenario: 'Full lifecycle with real-time customer notifications at each major stage', objective: 'Communication & transparency', expectedOutcome: 'All notifications sent, order completes', priority: 'high', category: 'integration' },
  { id: 'E2E-038', scenario: 'Chargeback / dispute filed after successful delivery', objective: 'Post-fulfillment financial reconciliation', expectedOutcome: 'Proof provided → dispute lost by customer → funds retained', priority: 'high', category: 'edge_case' },
  { id: 'E2E-039', scenario: 'Dry-run / simulated order (no real payment)', objective: 'End-to-end dry run validation', expectedOutcome: 'All steps execute except real money movement', priority: 'medium', category: 'edge_case' },
  { id: 'E2E-040', scenario: 'Super-bulk order exceeding single-batch capacity', objective: 'Multi-day / multi-batch production', expectedOutcome: 'Split production → cumulative delivery → full payment', priority: 'high', category: 'edge_case' },
  { id: 'E2E-041', scenario: 'Guest checkout (no account created)', objective: 'Anonymous order flow', expectedOutcome: 'Processed normally to delivery & bank', priority: 'high', category: 'happy_path' },
  { id: 'E2E-042', scenario: 'Pre-defined product bundle / set purchase', objective: 'Bundle pricing & assembly', expectedOutcome: 'Bundle assembled → delivered', priority: 'medium', category: 'happy_path' },
  { id: 'E2E-043', scenario: 'Slow payment gateway response / delayed authorization', objective: 'Asynchronous payment confirmation', expectedOutcome: 'Waits → confirms → proceeds', priority: 'high', category: 'edge_case' },
  { id: 'E2E-044', scenario: 'International order held in customs', objective: 'External customs & long-tail delivery tracking', expectedOutcome: 'Tracked → eventually cleared & delivered', priority: 'medium', category: 'integration' },
  { id: 'E2E-045', scenario: 'Customer-provided personalization contains typo / error', objective: '"As-is" manufacturing policy validation', expectedOutcome: 'Produced exactly as ordered → delivered (no refund assumed)', priority: 'low', category: 'edge_case' },
  { id: 'E2E-046', scenario: 'Loyalty points / store credit applied to reduce balance', objective: 'Partial alternative tender', expectedOutcome: 'Points deducted, balance paid, net correct amount in bank', priority: 'medium', category: 'integration' },
  { id: 'E2E-047', scenario: 'Temporary failure in payment → manufacturing API integration', objective: 'Retry logic & fault tolerance', expectedOutcome: 'Auto-retries → succeeds → completes flow', priority: 'high', category: 'edge_case' },
  { id: 'E2E-048', scenario: 'Upstream supply chain delay (external vendor)', objective: 'Delay notification & customer expectation management', expectedOutcome: 'Delay communicated → resolved → delivered', priority: 'medium', category: 'integration' },
  { id: 'E2E-049', scenario: 'Single order with split shipping addresses', objective: 'Multi-destination fulfillment', expectedOutcome: 'Correct items sent to each address, full payment', priority: 'medium', category: 'edge_case' },
  { id: 'E2E-050', scenario: 'Order shipped but returned as undeliverable / refused', objective: 'Return & full refund processing', expectedOutcome: 'Full refund issued, item restocked, net zero cash impact', priority: 'high', category: 'error_handling' }
];

export async function POST() {
  try {
    // Check if suite already exists
    const existing = await prisma.e2ETestSuite.findFirst({
      where: { name: 'Stuff Balls Autonomous E-Commerce System' }
    });

    if (existing) {
      return NextResponse.json({
        success: true,
        message: 'Suite already exists',
        suiteId: existing.id
      });
    }

    // Create the test suite
    const suite = await prisma.e2ETestSuite.create({
      data: {
        name: 'Stuff Balls Autonomous E-Commerce System',
        description: 'Comprehensive test suite covering the complete order lifecycle from order placement through manufacturing, fulfillment, delivery, and financial reconciliation.',
        version: '1.0',
        status: 'active',
        environment: 'staging',
        metadata: {
          testType: 'End-to-End (E2E) / System Integration / Business Process Validation',
          scope: 'Front-end → Order Management → Payment Gateway → Inventory → Autonomous Manufacturing → Quality Control → Packaging → Shipping → Carrier Integration → Delivery Confirmation → Accounting / Bank Reconciliation',
          preparedBy: 'Senior QA Engineer',
          date: 'March 2026'
        }
      }
    });

    // Create all test cases
    await prisma.e2ETestCase.createMany({
      data: STUFF_BALLS_TEST_CASES.map(tc => ({
        suiteId: suite.id,
        testCaseId: tc.id,
        scenario: tc.scenario,
        objective: tc.objective,
        expectedOutcome: tc.expectedOutcome,
        priority: tc.priority,
        category: tc.category,
        preconditions: [],
        testSteps: [],
        testData: {}
      }))
    });

    return NextResponse.json({
      success: true,
      message: 'Stuff Balls test suite created successfully',
      suiteId: suite.id,
      testCaseCount: STUFF_BALLS_TEST_CASES.length
    });
  } catch (error: any) {
    console.error('Error seeding test suite:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
