import { apiRequest, ApiRequestOptions } from './api';
import { ApiRequestError } from '../types/api';
import type { PackageWithStatus, PackageUpdate } from '../types/package';

/**
 * Make a request to the Pro REST API (sequensy-pro/v1 namespace).
 * Falls back to the free namespace if proRoot is not set.
 */
async function proApiRequest<T = unknown>(
  endpoint: string,
  options: ApiRequestOptions = {},
): Promise<T> {
  const proRoot = window.sequensyAPI.proRoot;
  if (!proRoot) {
    return apiRequest<T>(endpoint, options);
  }

  const { timeout = 30_000, ...fetchOptions } = options;

  let url: string;
  if (endpoint.includes('?')) {
    const [path, queryString] = endpoint.split('?');
    if (proRoot.includes('?')) {
      url = `${proRoot}${path}&${queryString}`;
    } else {
      url = `${proRoot}${endpoint}`;
    }
  } else {
    url = `${proRoot}${endpoint}`;
  }

  const headers: HeadersInit = {
    'Content-Type': 'application/json',
    'X-WP-Nonce': window.sequensyAPI.nonce,
    ...fetchOptions.headers,
  };

  const response = await fetch(url, { ...fetchOptions, headers });

  if (!response.ok) {
    let error: { message?: string; code?: string; data?: Record<string, unknown> } | undefined;
    try {
      error = await response.json();
    } catch {
      // not JSON
    }
    throw new ApiRequestError(
      error?.message || `Request failed with status ${response.status}`,
      error?.code || 'unknown_error',
      response.status,
      error?.data,
    );
  }

  return response.json();
}

export async function getAvailablePackages(
  category?: string,
  search?: string,
): Promise<PackageWithStatus[]> {
  const params = new URLSearchParams();
  if (category) params.set('category', category);
  if (search) params.set('search', search);
  const query = params.toString();
  return proApiRequest<PackageWithStatus[]>(`/packages${query ? `?${query}` : ''}`);
}

export async function installPackage(slug: string): Promise<{ success: boolean; message: string }> {
  return proApiRequest(`/packages/${slug}/install`, { method: 'POST' });
}

export async function updatePackage(slug: string): Promise<{ success: boolean; message: string }> {
  return proApiRequest(`/packages/${slug}/update`, { method: 'POST' });
}

export async function uninstallPackage(
  slug: string,
): Promise<{ success: boolean; message: string }> {
  return proApiRequest(`/packages/${slug}`, { method: 'DELETE' });
}

export async function activatePackage(
  slug: string,
): Promise<{ success: boolean; message: string }> {
  return proApiRequest(`/packages/${slug}/activate`, { method: 'POST' });
}

export async function deactivatePackage(
  slug: string,
  options?: { confirmDeactivateWorkflows?: boolean },
): Promise<{ success: boolean; message: string }> {
  const query = options?.confirmDeactivateWorkflows ? '?confirm_deactivate_workflows=1' : '';
  return proApiRequest(`/packages/${slug}/deactivate${query}`, { method: 'POST' });
}

export async function checkForUpdates(): Promise<PackageUpdate[]> {
  const response = await proApiRequest<{ success: boolean; updates: PackageUpdate[] }>(
    '/packages/check-updates',
    { method: 'POST' },
  );
  return response.updates ?? [];
}
