import { apiClient, getDataOrThrow } from "@/core/api";
import type {
  CancellationPreview,
  InternetCancelRequest,
} from "@customer-portal/domain/subscriptions";
import { cancellationPreviewSchema } from "@customer-portal/domain/subscriptions";

/**
 * Unified Cancellation API Service
 *
 * Single API for cancelling any service type (SIM or Internet).
 * Service type is auto-detected by the backend from the subscription product name.
 */
export const cancellationService = {
  /**
   * Get unified cancellation preview
   *
   * Returns service info, terms, warnings, and cancellation status (from Opportunity).
   * Service type is detected from subscription product name.
   */
  async getPreview(subscriptionId: string): Promise<CancellationPreview> {
    const response = await apiClient.GET<CancellationPreview>(
      "/api/subscriptions/{id}/cancel/preview",
      {
        params: { path: { id: subscriptionId } },
      }
    );

    const payload = getDataOrThrow(response, "Failed to load cancellation information");
    return cancellationPreviewSchema.parse(payload);
  },

  /**
   * Submit cancellation request
   *
   * Routes to appropriate handler based on service type (Freebit for SIM, Case for Internet).
   */
  async submit(subscriptionId: string, request: InternetCancelRequest): Promise<void> {
    await apiClient.POST("/api/subscriptions/{id}/cancel", {
      params: { path: { id: subscriptionId } },
      body: request,
    });
  },
};
