import { joinUrl, normaliseBaseUrl, toWebSocketUrl } from './httpPaths';

const DEFAULT_URL = 'https://shire-mini.local:8745';

export default class ShireScanBridgeClient {
  constructor(baseUrl = DEFAULT_URL) { this.baseUrl = normaliseBaseUrl(baseUrl || DEFAULT_URL); }
  setUrl(url) { this.baseUrl = normaliseBaseUrl(url); }
  setCredential(token) { sessionStorage.setItem('shire_bridge_credential', token); }
  getCredential() { return sessionStorage.getItem('shire_bridge_credential'); }
  forget() { sessionStorage.removeItem('shire_bridge_credential'); }

  async request(path, options = {}) {
    const token = this.getCredential();
    const response = await fetch(joinUrl(this.baseUrl, path), {
      ...options,
      headers: {
        Accept: 'application/json',
        ...(options.body ? { 'Content-Type': 'application/json' } : {}),
        ...(token ? { Authorization: `Bearer ${token}` } : {}),
        ...(options.headers || {})
      }
    });
    if (response.status === 401 || response.status === 403) throw new Error('BRIDGE_AUTHENTICATION_REQUIRED');
    if (!response.ok) throw new Error(`BRIDGE_REQUEST_FAILED (${response.status})`);
    return response.status === 204 ? null : response.json();
  }

  health() { return this.request('/api/v1/health'); }
  device() { return this.request('/api/v1/device'); }
  capabilities() { return this.request('/api/v1/capabilities'); }
  pair(code) { return this.post('/api/v1/pair', { code }); }
  post(path, body = {}) { return this.request(path, { method: 'POST', body: JSON.stringify(body) }); }
  startCalibration(body) { return this.post('/api/v1/calibration/start', body); }
  calibration(id) { return this.request(`/api/v1/calibration/${id}`); }
  createProject(body) { return this.post('/api/v1/projects', body); }
  getProject(id) { return this.request(`/api/v1/projects/${id}`); }
  capture(id, action, body) { return this.post(`/api/v1/projects/${id}/capture/${action}`, body); }
  captureStatus(id) { return this.request(`/api/v1/projects/${id}/capture/status`); }
  process(id, body) { return this.post(`/api/v1/projects/${id}/process`, body); }
  processStatus(id) { return this.request(`/api/v1/projects/${id}/process/status`); }
  meshAction(id, body) { return this.post(`/api/v1/projects/${id}/mesh/actions`, body); }
  meshVersions(id) { return this.request(`/api/v1/projects/${id}/mesh/versions`); }
  addMeasurement(id, body) { return this.post(`/api/v1/projects/${id}/measurements`, body); }
  printCheck(id, body) { return this.post(`/api/v1/projects/${id}/print-check`, body); }
  createExport(id, body) { return this.post(`/api/v1/projects/${id}/exports`, body); }
  getExport(id, exportId) { return this.request(`/api/v1/projects/${id}/exports/${exportId}`); }

  liveSocket(projectId) {
    const token = this.getCredential();
    const protocols = token ? [`shire-bridge-bearer.${token}`] : [];
    return new WebSocket(toWebSocketUrl(this.baseUrl, `/ws/v1/projects/${projectId}/live`), protocols);
  }
}

export { DEFAULT_URL };
