/**
 * Organizations API
 *
 * Endpoints for organization management
 */

import { get, post, patch } from './client';
import type {
  OrganizationResponse,
  OrganizationListResponse,
  CreateOrganizationRequest,
  UpdateOrganizationRequest,
} from '@/types/api';

/**
 * List organizations with pagination
 * GET /api/v1/organizations?page=1&limit=20&type=FREIGHT_FORWARDER&isActive=true
 * Requires: ADMIN role
 */
export async function listOrganizations(params?: {
  page?: number;
  limit?: number;
  type?: string;
  isActive?: boolean;
}): Promise<OrganizationListResponse> {
  const queryParams = new URLSearchParams();
  if (params?.page) queryParams.append('page', params.page.toString());
  if (params?.limit) queryParams.append('limit', params.limit.toString());
  if (params?.type) queryParams.append('type', params.type);
  if (params?.isActive !== undefined) queryParams.append('isActive', params.isActive.toString());

  const queryString = queryParams.toString();
  return get<OrganizationListResponse>(
    `/api/v1/organizations${queryString ? `?${queryString}` : ''}`
  );
}

/**
 * Get organization by ID
 * GET /api/v1/organizations/:id
 * Requires: Authenticated user (own org or admin)
 */
export async function getOrganization(id: string): Promise<OrganizationResponse> {
  return get<OrganizationResponse>(`/api/v1/organizations/${id}`);
}

/**
 * Create new organization
 * POST /api/v1/organizations
 * Requires: ADMIN role
 */
export async function createOrganization(
  data: CreateOrganizationRequest
): Promise<OrganizationResponse> {
  return post<OrganizationResponse>('/api/v1/organizations', data);
}

/**
 * Update organization
 * PATCH /api/v1/organizations/:id
 * Requires: ADMIN or MANAGER role (own org)
 */
export async function updateOrganization(
  id: string,
  data: UpdateOrganizationRequest
): Promise<OrganizationResponse> {
  return patch<OrganizationResponse>(`/api/v1/organizations/${id}`, data);
}
