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

import type { ApiResponse, PaginatedResult } from '@/shared/types/types'
import type { DisputeStatus } from '@/shared/types/status'

export interface Dispute {
  id: number
  order_id: number
  order_no: string
  order_status: string
  handoff_status: string
  settlement_status: string
  listing_no: string
  title: string
  owner_id: number
  renter_id: number
  owner_phone: string
  renter_phone: string
  initiator_id: number
  target_user_id: number
  type: string
  status: DisputeStatus
  description: string
  evidence_urls?: string[]
  previous_order_status?: string
  previous_handoff_status?: string
  previous_settlement_status?: string
  checkout_id?: number
  previous_checkout_status?: string
  arbitration_result: string
  arbitration_remark: string
  handled_by?: number
  handled_at?: string
  created_at: string
  updated_at: string
}

export interface AdminDisputeQuery {
  keyword?: string
  status?: string
  type?: string
}

export async function createDispute(
  orderId: number,
  payload: { type: string; description: string; evidence_urls?: string[] }
) {
  const { data } = await apiClient.post<ApiResponse<Dispute>>(`/orders/${orderId}/dispute`, payload)
  return data.data
}

export async function cancelOrderDispute(orderId: number) {
  const { data } = await apiClient.post<ApiResponse<Dispute>>(`/orders/${orderId}/dispute/cancel`)
  return data.data
}

export async function cancelDispute(id: number) {
  const { data } = await apiClient.post<ApiResponse<Dispute>>(`/disputes/${id}/cancel`)
  return data.data
}

export async function fetchDisputes(page = 1, pageSize = 20) {
  const { data } = await apiClient.get<ApiResponse<PaginatedResult<Dispute>>>('/disputes', {
    params: { page, page_size: pageSize },
  })
  return data.data
}

export async function fetchAdminDisputes(page = 1, pageSize = 20, query: AdminDisputeQuery = {}) {
  const { data } = await apiClient.get<ApiResponse<PaginatedResult<Dispute>>>('/admin/disputes', {
    params: { page, page_size: pageSize, ...query },
  })
  return data.data
}

export async function arbitrateDispute(
  id: number,
  payload: { result: string; remark: string; amount_cent?: number }
) {
  const { data } = await apiClient.post<ApiResponse<Dispute>>(
    `/admin/disputes/${id}/arbitrate`,
    payload
  )
  return data.data
}
