import * as THREE from 'three';
import { GLTFExporter } from 'three/examples/jsm/exporters/GLTFExporter.js';

/**
 * Generates a steel I-beam (IPE 200) as a GLB blob.
 * Dimensions in meters (model is 1:1 scale, original units mm).
 * IPE 200: h=200mm, b=100mm, tw=5.6mm, tf=8.5mm, length=1000mm
 */
export async function generateDemoBeamGLB(): Promise<{ blob: Blob; fileName: string; fileSize: number }> {
  const scene = new THREE.Scene();

  // IPE 200 dimensions in meters
  const h = 0.200;    // height
  const b = 0.100;    // flange width
  const tw = 0.0056;  // web thickness
  const tf = 0.0085;  // flange thickness
  const L = 1.0;      // length (1000mm)

  const material = new THREE.MeshStandardMaterial({
    color: 0x8899aa,
    metalness: 0.85,
    roughness: 0.35,
  });

  // Web (vertical plate in the center)
  const webHeight = h - 2 * tf;
  const webGeo = new THREE.BoxGeometry(L, webHeight, tw);
  const web = new THREE.Mesh(webGeo, material);
  web.position.set(0, 0, 0);

  // Top flange
  const topFlangeGeo = new THREE.BoxGeometry(L, tf, b);
  const topFlange = new THREE.Mesh(topFlangeGeo, material);
  topFlange.position.set(0, (webHeight + tf) / 2, 0);

  // Bottom flange
  const bottomFlangeGeo = new THREE.BoxGeometry(L, tf, b);
  const bottomFlange = new THREE.Mesh(bottomFlangeGeo, material);
  bottomFlange.position.set(0, -(webHeight + tf) / 2, 0);

  const group = new THREE.Group();
  group.name = 'IPE200_Steel_Beam';
  group.add(web, topFlange, bottomFlange);
  scene.add(group);

  // Export as GLB
  const exporter = new GLTFExporter();
  const glb = await new Promise<ArrayBuffer>((resolve, reject) => {
    exporter.parse(
      scene,
      (result) => resolve(result as ArrayBuffer),
      (error) => reject(error),
      { binary: true }
    );
  });

  const blob = new Blob([glb], { type: 'model/gltf-binary' });
  return {
    blob,
    fileName: 'Demo_IPE200_1000mm.glb',
    fileSize: blob.size,
  };
}
