// ================================================================
// frontend/src/api/services/orders.ts
// ================================================================
/**
 * Orders Service - Complete backend alignment
 *
 * Backend API structure (3-tier architecture):
 * - ATOMIC: orders.py, customers.py
 * - OPERATIONS: order_operations.py, procurement_operations.py
 *
 * Last Updated: 2025-10-05
 * Status: ✅ Complete - Zero drift with backend
 */

import { apiClient } from '../client/apiClient';
import {
  OrderResponse,
  OrderCreate,
  OrderUpdate,
  CustomerResponse,
  CustomerCreate,
  CustomerUpdate,
  OrdersDashboardSummary,
  DemandRequirements,
  BusinessModelDetection,
  ServiceStatus,
  GetOrdersParams,
  GetCustomersParams,
  UpdateOrderStatusParams,
  GetDemandRequirementsParams,
} from '../types/orders';

export class OrdersService {
  // ===================================================================
  // OPERATIONS: Dashboard & Analytics
  // Backend: services/orders/app/api/order_operations.py
  // ===================================================================

  /**
   * Get comprehensive dashboard summary for orders
   * GET /tenants/{tenant_id}/orders/operations/dashboard-summary
   */
  static async getDashboardSummary(tenantId: string): Promise<OrdersDashboardSummary> {
    return apiClient.get<OrdersDashboardSummary>(`/tenants/${tenantId}/orders/operations/dashboard-summary`);
  }

  /**
   * Get demand requirements for production planning
   * GET /tenants/{tenant_id}/orders/operations/demand-requirements
   */
  static async getDemandRequirements(params: GetDemandRequirementsParams): Promise<DemandRequirements> {
    const { tenant_id, target_date } = params;
    return apiClient.get<DemandRequirements>(
      `/tenants/${tenant_id}/orders/operations/demand-requirements?target_date=${target_date}`
    );
  }

  // ===================================================================
  // ATOMIC: Orders CRUD
  // Backend: services/orders/app/api/orders.py
  // ===================================================================

  /**
   * Create a new customer order
   * POST /tenants/{tenant_id}/orders
   */
 static async createOrder(orderData: OrderCreate): Promise<OrderResponse> {
    const { tenant_id } = orderData;
    // Note: tenant_id is in both URL path and request body (backend schema requirement)
    return apiClient.post<OrderResponse>(`/tenants/${tenant_id}/orders`, orderData);
  }

  /**
   * Get order details with items
   * GET /tenants/{tenant_id}/orders/{order_id}
   */
  static async getOrder(tenantId: string, orderId: string): Promise<OrderResponse> {
    return apiClient.get<OrderResponse>(`/tenants/${tenantId}/orders/${orderId}`);
  }

  /**
   * Get orders with filtering and pagination
   * GET /tenants/{tenant_id}/orders
   */
  static async getOrders(params: GetOrdersParams): Promise<OrderResponse[]> {
    const { tenant_id, status_filter, start_date, end_date, skip = 0, limit = 100 } = params;
    
    const queryParams = new URLSearchParams({
      skip: skip.toString(),
      limit: limit.toString(),
    });

    if (status_filter) {
      queryParams.append('status_filter', status_filter);
    }
    if (start_date) {
      queryParams.append('start_date', start_date);
    }
    if (end_date) {
      queryParams.append('end_date', end_date);
    }

    return apiClient.get<OrderResponse[]>(`/tenants/${tenant_id}/orders?${queryParams.toString()}`);
  }

  /**
   * Update order details
   * PUT /tenants/{tenant_id}/orders/{order_id}
   */
  static async updateOrder(tenantId: string, orderId: string, orderData: OrderUpdate): Promise<OrderResponse> {
    return apiClient.put<OrderResponse>(`/tenants/${tenantId}/orders/${orderId}`, orderData);
  }

  /**
   * Update order status
   * PUT /tenants/{tenant_id}/orders/{order_id}/status
   */
  static async updateOrderStatus(params: UpdateOrderStatusParams): Promise<OrderResponse> {
    const { tenant_id, order_id, new_status, reason } = params;

    const queryParams = new URLSearchParams();
    if (reason) {
      queryParams.append('reason', reason);
    }

    const url = `/tenants/${tenant_id}/orders/${order_id}/status${queryParams.toString() ? `?${queryParams.toString()}` : ''}`;

    return apiClient.put<OrderResponse>(url, { status: new_status });
  }

  // ===================================================================
  // ATOMIC: Customers CRUD
  // Backend: services/orders/app/api/customers.py
  // ===================================================================

  /**
   * Create a new customer
   * POST /tenants/{tenant_id}/orders/customers
   */
  static async createCustomer(customerData: CustomerCreate): Promise<CustomerResponse> {
    const { tenant_id, ...data } = customerData;
    return apiClient.post<CustomerResponse>(`/tenants/${tenant_id}/orders/customers`, data);
  }

  /**
   * Get customers with filtering and pagination
   * GET /tenants/{tenant_id}/customers
   */
  static async getCustomers(params: GetCustomersParams): Promise<CustomerResponse[]> {
    const { tenant_id, active_only = true, skip = 0, limit = 100 } = params;
    
    const queryParams = new URLSearchParams({
      active_only: active_only.toString(),
      skip: skip.toString(),
      limit: limit.toString(),
    });

    return apiClient.get<CustomerResponse[]>(`/tenants/${tenant_id}/orders/customers?${queryParams.toString()}`);
  }

  /**
   * Get customer details
   * GET /tenants/{tenant_id}/customers/{customer_id}
   */
  static async getCustomer(tenantId: string, customerId: string): Promise<CustomerResponse> {
    return apiClient.get<CustomerResponse>(`/tenants/${tenantId}/orders/customers/${customerId}`);
  }

  /**
   * Update customer details
   * PUT /tenants/{tenant_id}/customers/{customer_id}
   */
  static async updateCustomer(tenantId: string, customerId: string, customerData: CustomerUpdate): Promise<CustomerResponse> {
    return apiClient.put<CustomerResponse>(`/tenants/${tenantId}/orders/customers/${customerId}`, customerData);
  }

  // ===================================================================
  // OPERATIONS: Business Intelligence
  // Backend: services/orders/app/api/order_operations.py
  // ===================================================================

  /**
   * Detect business model based on order patterns
   * GET /tenants/{tenant_id}/orders/operations/business-model
   */
  static async detectBusinessModel(tenantId: string): Promise<BusinessModelDetection> {
    return apiClient.get<BusinessModelDetection>(`/tenants/${tenantId}/orders/operations/business-model`);
  }

  // ===================================================================
  // Health Check
  // ===================================================================

  /**
   * Get orders service status
   * GET /tenants/{tenant_id}/orders/operations/status
   */
  static async getServiceStatus(tenantId: string): Promise<ServiceStatus> {
    return apiClient.get<ServiceStatus>(`/tenants/${tenantId}/orders/operations/status`);
  }

}

export default OrdersService;
