import { apiClient } from '@/shared/api/client'

export type AdminOrderListItem = {
  id: string
  status: string
  deliveryType: 'delivery' | 'pickup'
  deliveryCarrier?: string | null
  paymentMethod?: 'online' | 'on_pickup'
  totalCents: number
  currency: string
  createdAt: string
  updatedAt: string
  user: { id: string; email: string }
  itemsCount: number
}

export type AdminOrdersListResponse = {
  items: AdminOrderListItem[]
  total: number
  page: number
  pageSize: number
}

export type AdminOrderDetailResponse = {
  item: {
    id: string
    status: string
    deliveryType: 'delivery' | 'pickup'
    deliveryCarrier?: string | null
    paymentMethod?: 'online' | 'on_pickup'
    itemsSubtotalCents: number
    deliveryFeeCents: number
    totalCents: number
    currency: string
    addressSnapshotJson: string | null
    comment: string | null
    createdAt: string
    updatedAt: string
    user: { id: string; email: string; name: string | null; phone: string | null }
    items: Array<{
      id: string
      productId: string
      qty: number
      titleSnapshot: string
      priceCentsSnapshot: number
    }>
    messages: Array<{
      id: string
      authorType: string
      text: string
      attachmentUrl?: string | null
      createdAt: string
    }>
  }
}

export async function fetchAdminOrdersSummary(): Promise<{ attentionCount: number }> {
  const { data } = await apiClient.get<{ attentionCount: number }>('admin/orders/summary')
  return data
}

export async function fetchAdminOrders(params?: {
  status?: string
  deliveryType?: 'delivery' | 'pickup'
  q?: string
  page?: number
  pageSize?: number
}): Promise<AdminOrdersListResponse> {
  const { data } = await apiClient.get<AdminOrdersListResponse>('admin/orders', { params })
  return data
}

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

export async function setAdminOrderStatus(id: string, status: string): Promise<void> {
  await apiClient.patch(`admin/orders/${id}/status`, { status })
}

export async function patchAdminOrderDeliveryFee(id: string, deliveryFeeCents: number): Promise<void> {
  await apiClient.patch(`admin/orders/${id}/delivery-fee`, { deliveryFeeCents })
}

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