/**
 * FedEx REST API Types
 * Type definitions for FedEx Ship, Track, and Auth APIs
 * API Version: v1 (REST)
 */

// ─── Authentication ──────────────────────────────────────────────

export interface FedExAuthResponse {
  access_token: string
  token_type: "bearer"
  expires_in: number
  scope: string
}

// ─── Address & Contact ───────────────────────────────────────────

export interface FedExAddress {
  streetLines: string[]
  city: string
  stateOrProvinceCode: string
  postalCode: string
  countryCode: string
  residential?: boolean
}

export interface FedExContact {
  personName: string
  phoneNumber: string
  emailAddress?: string
  companyName?: string
}

export interface FedExParty {
  contact: FedExContact
  address: FedExAddress
}

// ─── Ship API: Create Shipment ───────────────────────────────────

export interface FedExWeight {
  units: "LB" | "KG"
  value: number
}

export interface FedExDimensions {
  length: number
  width: number
  height: number
  units: "IN" | "CM"
}

export interface FedExCustomerReference {
  customerReferenceType: "CUSTOMER_REFERENCE" | "INVOICE_NUMBER" | "P_O_NUMBER"
  value: string
}

export interface FedExPackageLineItem {
  weight: FedExWeight
  dimensions?: FedExDimensions
  customerReferences?: FedExCustomerReference[]
  itemDescription?: string
  itemDescriptionForClearance?: string
}

export interface FedExShipmentRequest {
  accountNumber: {
    value: string
  }
  requestedShipment: {
    shipper: FedExParty
    recipients: FedExParty[]
    pickupType: "DROPOFF_AT_FEDEX_LOCATION" | "CONTACT_FEDEX_TO_SCHEDULE" | "USE_SCHEDULED_PICKUP"
    serviceType: FedExServiceType
    packagingType: "YOUR_PACKAGING" | "FEDEX_BOX" | "FEDEX_ENVELOPE" | "FEDEX_PAK" | "FEDEX_TUBE"
    shippingChargesPayment: {
      paymentType: "SENDER" | "RECIPIENT" | "THIRD_PARTY"
      payor?: {
        responsibleParty: {
          accountNumber: {
            value: string
          }
        }
      }
    }
    labelSpecification?: {
      labelFormatType?: "COMMON2D" | "LABEL_DATA_ONLY"
      imageType?: "PDF" | "PNG" | "ZPLII"
      labelStockType?: string
    }
    requestedPackageLineItems: FedExPackageLineItem[]
    shipmentSpecialServices?: {
      specialServiceTypes?: string[]
    }
  }
  labelResponseOptions?: "URL_ONLY" | "LABEL"
}

// ─── Ship API: Create Shipment Response ──────────────────────────

export interface FedExPieceResponse {
  masterTrackingNumber: string
  trackingNumber: string
  additionalChargesDiscount?: number
  netRateAmount?: number
  netChargeAmount?: number
  netDiscountAmount?: number
  packageDocuments?: Array<{
    url?: string
    contentType?: string
    copiesToPrint?: number
    docType?: string
  }>
  deliveryDatestamp?: string
}

export interface FedExTransactionShipment {
  masterTrackingNumber: string
  serviceType: string
  shipDatestamp: string
  serviceName: string
  pieceResponses: FedExPieceResponse[]
  completedShipmentDetail?: {
    operationalDetail?: {
      originLocationIds?: string[]
      destinationLocationIds?: string[]
    }
  }
}

export interface FedExShipmentResponse {
  transactionId: string
  output: {
    transactionShipments: FedExTransactionShipment[]
    alerts?: Array<{
      code: string
      alertType: string
      message: string
    }>
  }
}

// ─── Ship API: Cancel Shipment ───────────────────────────────────

export interface FedExCancelRequest {
  accountNumber: {
    value: string
  }
  trackingNumber: string
  senderCountryCode?: string
  deletionControl?: "DELETE_ALL_PACKAGES" | "DELETE_ONE_PACKAGE"
}

export interface FedExCancelResponse {
  output: {
    cancelledShipment: boolean
    successMessage?: string
    alerts?: Array<{
      code: string
      alertType: string
      message: string
    }>
  }
}

// ─── Track API ───────────────────────────────────────────────────

export interface FedExTrackRequest {
  trackingInfo: Array<{
    trackingNumberInfo: {
      trackingNumber: string
    }
  }>
  includeDetailedScans: boolean
}

export interface FedExTrackEvent {
  date: string
  eventType: string
  eventDescription: string
  city?: string
  stateOrProvinceCode?: string
  postalCode?: string
  countryCode?: string
  residentialDelivery?: boolean
}

export interface FedExTrackResult {
  trackingNumber: string
  latestStatusDetail?: {
    code: string
    derivedCode: string
    statusByLocale: string
    description: string
    scanLocation?: {
      city: string
      stateOrProvinceCode: string
      countryCode: string
    }
  }
  dateAndTimes?: Array<{
    type: string
    dateTime: string
  }>
  deliveryDetails?: {
    actualDeliveryAddress?: FedExAddress
    deliveryAttempts?: string
  }
  scanEvents?: FedExTrackEvent[]
  delayDetail?: {
    status: "ON_TIME" | "EARLY" | "DELAYED"
  }
  estimatedDeliveryTimeWindow?: {
    window?: {
      begins: string
      ends: string
    }
  }
}

export interface FedExTrackResponse {
  output: {
    completeTrackResults: Array<{
      trackingNumber: string
      trackResults: FedExTrackResult[]
    }>
  }
}

// ─── FedEx Webhook (Tracking Updates) ────────────────────────────

export interface FedExWebhookPayload {
  trackingNumber: string
  eventType: string
  eventDescription: string
  eventTimestamp: string
  shipperAddress?: Partial<FedExAddress>
  recipientAddress?: Partial<FedExAddress>
  statusCode?: string
}

// ─── Error Response ──────────────────────────────────────────────

export interface FedExErrorResponse {
  transactionId?: string
  errors?: Array<{
    code: string
    message: string
    parameterList?: Array<{
      key: string
      value: string
    }>
  }>
}

// ─── Internal Result Type ────────────────────────────────────────

export interface FedExShipmentResult {
  success: boolean
  trackingNumber?: string
  shipDate?: string
  error?: string
  errorDetails?: any
}

// ─── Service Types ───────────────────────────────────────────────

export type FedExServiceType =
  | "FEDEX_GROUND"
  | "GROUND_HOME_DELIVERY"
  | "FEDEX_EXPRESS_SAVER"
  | "FEDEX_2_DAY"
  | "FEDEX_2_DAY_AM"
  | "STANDARD_OVERNIGHT"
  | "PRIORITY_OVERNIGHT"
  | "FIRST_OVERNIGHT"
  | "FEDEX_FREIGHT_ECONOMY"
  | "FEDEX_FREIGHT_PRIORITY"
  | "INTERNATIONAL_ECONOMY"
  | "INTERNATIONAL_PRIORITY"
  | "INTERNATIONAL_FIRST"
  | "SMART_POST"
