import axios from 'axios';
import { getRaspberryHost, getRaspberryPort, getToken } from '../config.js';

interface RunTaskParams {
  task: string;
}

interface AudioLockParams {
  filename: string;
}

export const raspiService = {
  async runTask(params: RunTaskParams) {
    const res = await axios.post(`${getRaspberryHost()}:${getRaspberryPort()}/run`, null, {
      params: { task: params.task, token: getToken() },
    });
    return res.data;
  },

  async motorStepForward() {
    const res = await axios.post(`${getRaspberryHost()}:${getRaspberryPort()}/motor/step/forward`, null, {
      params: { token: getToken() },
    });
    return res.data;
  },

  async motorStepBackward() {
    const res = await axios.post(`${getRaspberryHost()}:${getRaspberryPort()}/motor/step/backwards`, null, {
      params: { token: getToken() },
    });
    return res.data;
  },

  async motorStop() {
    const res = await axios.post(`${getRaspberryHost()}:${getRaspberryPort()}/motor/stop`, null, {
      params: { token: getToken() },
    });
    return res.data;
  },

  async uploadAudio(buffer: Buffer, filename?: string) {
    const fname = filename || 'audio.wav';
    const ext = fname.split('.').pop()?.toLowerCase() || 'wav';
    const formData = new FormData();
    formData.append('file', new Blob([buffer]), fname);
    const res = await axios.post(`${getRaspberryHost()}:${getRaspberryPort()}/audio/upload`, formData, {
      params: { format: ext },
      headers: { 'Content-Type': 'multipart/form-data' },
    });
    return res.data;
  },

  async listIncomingAudio() {
    const res = await axios.get(`${getRaspberryHost()}:${getRaspberryPort()}/audio/incoming`);
    return res.data;
  },

  async lockAudio(params: AudioLockParams) {
    const res = await axios.post(`${getRaspberryHost()}:${getRaspberryPort()}/audio/lock/${params.filename}`);
    return res.data;
  },

  async unlockAudio(params: AudioLockParams) {
    const res = await axios.post(`${getRaspberryHost()}:${getRaspberryPort()}/audio/unlock/${params.filename}`);
    return res.data;
  },

  async cancelAudio(params: AudioLockParams) {
    const res = await axios.post(`${getRaspberryHost()}:${getRaspberryPort()}/audio/cancel/${params.filename}`);
    return res.data;
  },

  async processAudio(params: AudioLockParams) {
    const res = await axios.post(`${getRaspberryHost()}:${getRaspberryPort()}/audio/process/${params.filename}`);
    return res.data;
  },
};
