import { Router } from 'express';
import multer from 'multer';
import { raspiService } from '../services/raspi.service.js';

const router = Router();

// Multer config - store in memory for proxying to RasPi
const upload = multer({ storage: multer.memoryStorage() });

router.post('/step/forward', async (_req, res) => {
  try {
    const result = await raspiService.motorStepForward();
    res.json(result);
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : 'Unknown error';
    res.status(500).json({ error: `Motor step forward failed: ${message}` });
  }
});

router.post('/step/backward', async (_req, res) => {
  try {
    const result = await raspiService.motorStepBackward();
    res.json(result);
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : 'Unknown error';
    res.status(500).json({ error: `Motor step backward failed: ${message}` });
  }
});

router.post('/stop', async (_req, res) => {
  try {
    const result = await raspiService.motorStop();
    res.json(result);
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : 'Unknown error';
    res.status(500).json({ error: `Motor stop failed: ${message}` });
  }
});

router.post('/upload', upload.single('file'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: 'No audio file provided' });
    }
    const result = await raspiService.uploadAudio(req.file.buffer, req.file.originalname);
    res.json(result);
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : 'Unknown error';
    res.status(500).json({ error: `Audio upload failed: ${message}` });
  }
});

export default router;
