// Weft Sandbox - Mock Data Provider

import { MockDataProvider } from './types';

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

  return {
    data,
    get(path: string): unknown {
      const keys = path.split('.');
      let current: unknown = data;
      for (const key of keys) {
        if (current && typeof current === 'object' && key in current) {
          current = (current as Record<string, unknown>)[key];
        } else {
          return undefined;
        }
      }
      return current;
    },
    set(path: string, value: unknown): void {
      const keys = path.split('.');
      let current: Record<string, unknown> = data;
      for (let i = 0; i < keys.length - 1; i++) {
        if (!(keys[i] in current)) {
          current[keys[i]] = {};
        }
        current = current[keys[i]] as Record<string, unknown>;
      }
      current[keys[keys.length - 1]] = value;
    },
    reset(): void {
      data = JSON.parse(JSON.stringify(originalData));
    },
    export(): Record<string, unknown> {
      return JSON.parse(JSON.stringify(data));
    }
  };
}

export function generateMockFromSchema(schema: Record<string, string>): Record<string, unknown> {
  const mock: Record<string, unknown> = {};
  for (const [key, type] of Object.entries(schema)) {
    switch (type.toLowerCase()) {
      case 'string':
        mock[key] = `mock_${key}`;
        break;
      case 'number':
      case 'int':
      case 'integer':
        mock[key] = Math.floor(Math.random() * 100);
        break;
      case 'boolean':
      case 'bool':
        mock[key] = Math.random() > 0.5;
        break;
      case 'date':
      case 'datetime':
        mock[key] = new Date().toISOString();
        break;
      case 'array':
        mock[key] = [];
        break;
      case 'object':
        mock[key] = {};
        break;
      default:
        mock[key] = null;
    }
  }
  return mock;
}
