import { API_ENDPOINTS } from '@/shared/constants/apiEndpoints';
import type { TicketAttachment } from '@/features/tickets/types/ticket.types';

function isAbsoluteUrl(url: string): boolean {
  return /^https?:\/\//i.test(url);
}

function isStoragePath(url: string): boolean {
  return url.startsWith('/storage/') || url.includes('/storage/');
}

function isApiPath(url: string): boolean {
  return url.startsWith('/api/');
}

/**
 * Normalize attachment URLs from the API for browser use (links, img src).
 * Never prefix /storage paths with /api/v1 — Laravel serves those at /storage/{path}.
 * Prefer the authenticated download route for reliable access to private files.
 */
export function resolveAttachmentUrl(attachment: TicketAttachment, options?: { inline?: boolean }): string {
  const inline = options?.inline ?? false;
  const downloadPath = attachment.download_url
    ? normalizePath(attachment.download_url)
    : `/api/v1${API_ENDPOINTS.ATTACHMENTS.DOWNLOAD(attachment.id)}`;

  const rawUrl = attachment.url?.trim();
  if (!rawUrl) {
    return appendInlineQuery(downloadPath, inline);
  }

  if (isAbsoluteUrl(rawUrl)) {
    return rawUrl;
  }

  if (isStoragePath(rawUrl)) {
    // Unsigned /storage URLs fail for private disks; use authenticated download instead.
    return appendInlineQuery(downloadPath, inline);
  }

  if (isApiPath(rawUrl)) {
    return appendInlineQuery(normalizePath(rawUrl), inline);
  }

  // Legacy relative API paths (e.g. /attachments/{id}/download)
  return appendInlineQuery(`/api/v1${rawUrl.startsWith('/') ? rawUrl : `/${rawUrl}`}`, inline);
}

export function resolveAttachmentPreviewUrl(attachment: TicketAttachment): string {
  const isImage =
    attachment.mime_type?.startsWith('image/') ||
    /\.(jpe?g|png|gif|webp|bmp|svg)$/i.test(attachment.file_name ?? '');

  return resolveAttachmentUrl(attachment, { inline: isImage });
}

function normalizePath(path: string): string {
  if (isAbsoluteUrl(path)) {
    try {
      const { pathname, search } = new URL(path);
      if (pathname.startsWith('/api/')) {
        return `${pathname}${search}`;
      }
    } catch {
      return path;
    }
    return path;
  }
  if (path.startsWith('/api/')) {
    return path;
  }
  return path.startsWith('/') ? `/api/v1${path}` : `/api/v1/${path}`;
}

function appendInlineQuery(url: string, inline: boolean): string {
  if (!inline || !url.includes('/download')) {
    return url;
  }
  return url.includes('?') ? `${url}&inline=1` : `${url}?inline=1`;
}
