import { apiClient } from '@/shared/api/client'
import type { DeliveryCarrierCode } from '@/shared/constants/delivery-carrier'

export type OrderListItem = {
  id: string
  status: string
  totalCents: number
  currency: string
  createdAt: string
  updatedAt: string
  itemsCount: number
}

export type OrderListResponse = { items: OrderListItem[] }

export type OrderPaymentMethod = 'online' | 'on_pickup'

export type OrderDetailResponse = {
  item: {
    id: string
    status: string
    deliveryType: 'delivery' | 'pickup'
    deliveryCarrier?: DeliveryCarrierCode | null
    paymentMethod?: OrderPaymentMethod
    itemsSubtotalCents: number
    deliveryFeeCents: number
    totalCents: number
    currency: string
    addressSnapshotJson: string | null
    comment: string | null
    createdAt: string
    updatedAt: string
    items: Array<{
      id: string
      productId: string
      qty: number
      titleSnapshot: string
      priceCentsSnapshot: number
    }>
    messages: Array<{
      id: string
      authorType: 'user' | 'admin'
      text: string
      attachmentUrl?: string | null
      createdAt: string
    }>
  }
}

export async function createOrder(body: {
  deliveryType: 'delivery' | 'pickup'
  deliveryCarrier?: DeliveryCarrierCode | null
  paymentMethod?: OrderPaymentMethod
  addressId?: string | null
  comment?: string | null
}): Promise<{ orderId: string }> {
  const { data } = await apiClient.post<{ orderId: string }>('me/orders', body)
  return data
}

export async function fetchMyOrders(): Promise<OrderListResponse> {
  const { data } = await apiClient.get<OrderListResponse>('me/orders')
  return data
}

export async function fetchMyOrder(id: string): Promise<OrderDetailResponse> {
  const { data } = await apiClient.get<OrderDetailResponse>(`me/orders/${id}`)
  return data
}

export async function postOrderMessage(id: string, text: string): Promise<void> {
  await apiClient.post(`me/orders/${id}/messages`, { text })
}

/** Подтверждение оплаты переводом: multipart detail + необязательный файл receipt (хотя бы одно нужно на сервере). */
export async function submitOrderPayment(
  orderId: string,
  payload: { detail: string; receiptFile: File | null },
): Promise<{ ok: boolean; status: string }> {
  const formData = new FormData()
  formData.append('detail', payload.detail)
  if (payload.receiptFile) {
    formData.append('receipt', payload.receiptFile)
  }
  const { data } = await apiClient.post<{ ok: boolean; status: string }>(`me/orders/${orderId}/pay`, formData)
  return data
}

export async function confirmOrderReceived(id: string): Promise<{ ok: boolean; status: string }> {
  const { data } = await apiClient.post<{ ok: boolean; status: string }>(`me/orders/${id}/confirm-received`)
  return data
}

export type ReviewEligibilityItem = { productId: string; title: string; hasReview: boolean }

export async function fetchOrderReviewEligibility(orderId: string): Promise<{
  canReview: boolean
  items: ReviewEligibilityItem[]
}> {
  const { data } = await apiClient.get<{ canReview: boolean; items: ReviewEligibilityItem[] }>(
    `me/orders/${orderId}/review-eligibility`,
  )
  return data
}
