const APP_BASENAME = '/asm_app';

/**
 * Convert a scanned QR payload into an in-app React Router path (without basename).
 * Examples:
 *   http://host/asm_app/assets/ACC-ASS-2026-00002  → /assets/ACC-ASS-2026-00002
 *   /asm_app/assets/ACC-ASS-2026-00002             → /assets/ACC-ASS-2026-00002
 *   /assets/ACC-ASS-2026-00002                     → /assets/ACC-ASS-2026-00002
 *   ACC-ASS-2026-00002                             → /assets/ACC-ASS-2026-00002
 */
export function parseQrPayloadToAppPath(raw: string): string | null {
  const text = (raw || '').trim();
  if (!text) return null;

  let path = text;

  try {
    if (/^https?:\/\//i.test(text)) {
      const url = new URL(text);
      path = url.pathname + url.search + url.hash;
    }
  } catch {
    // keep raw text
  }

  // Strip app basename so react-router can navigate inside the SPA
  if (path.startsWith(APP_BASENAME + '/') || path === APP_BASENAME) {
    path = path.slice(APP_BASENAME.length) || '/';
  }

  // Absolute app-relative path already (e.g. /assets/...)
  if (path.startsWith('/')) {
    return path.split('?')[0] || path;
  }

  // Bare asset / work order id
  if (/^(ACC-ASS-|AST-|ACC-WO-)/i.test(path) || /^[A-Z0-9-]+$/i.test(path)) {
    if (/^(ACC-WO-|WO-)/i.test(path)) {
      return `/work-orders/${path}`;
    }
    return `/assets/${path}`;
  }

  return null;
}

export function isAssetAppPath(path: string): boolean {
  return /^\/assets\/[^/]+$/i.test(path.split('?')[0]);
}
