// Weft Sandbox - Mock Data Provider

import { MockDataProvider } from './types';

export function createMockProvider(initialData: Record<string, any> = {}): MockDataProvider {
  let data = JSON.parse(JSON.stringify(initialData)); // Deep clone
  const originalData = JSON.parse(JSON.stringify(initialData));

  return {
    data,

    get(path: string): any {
      const keys = path.split('.');
      let result: any = data;
      
      for (const key of keys) {
        if (result === undefined || result === null) return undefined;
        result = result[key];
      }
      
      return result;
    },

    set(path: string, value: any): void {
      const keys = path.split('.');
      let current: any = data;
      
      for (let i = 0; i < keys.length - 1; i++) {
        if (!(keys[i] in current)) {
          current[keys[i]] = {};
        }
        current = current[keys[i]];
      }
      
      current[keys[keys.length - 1]] = value;
    },

    reset(): void {
      data = JSON.parse(JSON.stringify(originalData));
    },

    export(): Record<string, any> {
      return JSON.parse(JSON.stringify(data));
    }
  };
}

// Auto-generate mock data from schema
export function generateMockFromSchema(schema: Record<string, string>): Record<string, any> {
  const mockData: Record<string, any> = {};

  for (const [key, type] of Object.entries(schema)) {
    mockData[key] = generateValueForType(type, key);
  }

  return mockData;
}

function generateValueForType(type: string, fieldName: string): any {
  const lowerName = fieldName.toLowerCase();
  const lowerType = type.toLowerCase();

  // Smart field detection
  if (lowerName.includes('email')) return 'demo@example.com';
  if (lowerName.includes('phone')) return '(555) 123-4567';
  if (lowerName.includes('name') && lowerName.includes('company')) return 'Acme Corporation';
  if (lowerName.includes('name')) return 'John Smith';
  if (lowerName.includes('price') || lowerName.includes('cost') || lowerName.includes('amount')) return 99.99;
  if (lowerName.includes('quantity') || lowerName.includes('qty') || lowerName.includes('count')) return 10;
  if (lowerName.includes('date')) return new Date().toISOString().split('T')[0];
  if (lowerName.includes('id')) return `ID-${Date.now().toString(36).toUpperCase()}`;
  if (lowerName.includes('status')) return 'active';
  if (lowerName.includes('description') || lowerName.includes('notes')) return 'Sample description text for testing purposes.';

  // Type-based generation
  if (lowerType.includes('string')) return 'Sample Text';
  if (lowerType.includes('number') || lowerType.includes('int') || lowerType.includes('float')) return 42;
  if (lowerType.includes('boolean') || lowerType.includes('bool')) return true;
  if (lowerType.includes('array') || lowerType.includes('[]')) return [];
  if (lowerType.includes('object')) return {};
  if (lowerType.includes('date')) return new Date().toISOString();

  return 'mock_value';
}

// Generate realistic entity data
export function generateEntityMock(entityType: string, count: number = 3): any[] {
  const templates: Record<string, () => any> = {
    customer: () => ({
      id: `C${String(Math.floor(Math.random() * 1000)).padStart(3, '0')}`,
      name: ['Acme Corp', 'Globex Inc', 'Initech', 'Umbrella Ltd', 'Wayne Enterprises'][Math.floor(Math.random() * 5)],
      email: `contact@${['acme', 'globex', 'initech', 'umbrella', 'wayne'][Math.floor(Math.random() * 5)]}.com`,
      creditLimit: Math.floor(Math.random() * 100000) + 10000,
      status: ['active', 'pending', 'vip'][Math.floor(Math.random() * 3)]
    }),
    product: () => ({
      sku: `SKU-${String(Math.floor(Math.random() * 10000)).padStart(4, '0')}`,
      name: ['Widget Alpha', 'Gadget Pro', 'Component X', 'Module Z', 'Unit Prime'][Math.floor(Math.random() * 5)],
      price: Math.floor(Math.random() * 500) + 10 + 0.99,
      stock: Math.floor(Math.random() * 200),
      category: ['Electronics', 'Hardware', 'Software', 'Services'][Math.floor(Math.random() * 4)]
    }),
    order: () => ({
      id: `ORD-${Date.now().toString(36).toUpperCase()}`,
      customerId: `C${String(Math.floor(Math.random() * 100)).padStart(3, '0')}`,
      total: Math.floor(Math.random() * 5000) + 100 + 0.99,
      status: ['pending', 'processing', 'shipped', 'delivered'][Math.floor(Math.random() * 4)],
      createdAt: new Date(Date.now() - Math.floor(Math.random() * 7 * 24 * 60 * 60 * 1000)).toISOString()
    }),
    warehouse: () => ({
      id: `WH-${['NORTH', 'SOUTH', 'EAST', 'WEST', 'CENTRAL'][Math.floor(Math.random() * 5)]}`,
      name: ['North Distribution', 'South Hub', 'East Warehouse', 'West Facility', 'Central Storage'][Math.floor(Math.random() * 5)],
      capacity: Math.floor(Math.random() * 10000) + 1000,
      utilization: Math.floor(Math.random() * 100)
    })
  };

  const generator = templates[entityType.toLowerCase()] || templates.product;
  return Array.from({ length: count }, generator);
}
