import adminClient from "./client"
import type { ApiResponse } from "../../types"
import type { ServiceOrder } from "../../api/orders"
import { listResult } from "./response"

export interface AdminServiceOrderUser {
  id: number
  username: string | null
  email: string | null
  phone: string | null
  nickname: string | null
}

export interface AdminResourceSummary {
  status: "none" | "running" | "failed" | "finished" | "manual_handled" | "ignored" | string
  label: string
  failed_count: number
  running_count: number
}

export interface AdminServiceOrder extends ServiceOrder {
  user: AdminServiceOrderUser
  resource_summary: AdminResourceSummary
}

export interface AdminServiceOrderFilters {
  keyword?: string
  status?: string
  refund_status?: string
  refund_type?: string
  resource_status?: string
  user_id?: number
  instance_id?: number
  limit?: number
  offset?: number
}

export interface AdminServiceOrderUnsubscribeResult {
  refunds: Array<{
    refund: AdminServiceOrder["refund"]
    order: AdminServiceOrder
  }>
  total_refund: number
  instance_deleted: boolean
}

const DEFAULT_RESOURCE_SUMMARY: AdminResourceSummary = {
  status: "none",
  label: "无资源动作",
  failed_count: 0,
  running_count: 0,
}

const DEFAULT_REFUND_POLICY: AdminServiceOrder["refund_policy"] = {
  action_allowed: false,
  refund_type: "unavailable",
  refund_amount: 0,
  paid_amount: 0,
  reason: "暂无可退订信息",
  points_claimed: false,
  full_refund_used: 0,
  full_refund_limit: 0,
  full_refund_days: 0,
  within_full_refund_window: false,
  latest_refund: null,
}

function normalizeAdminServiceOrder(order: AdminServiceOrder): AdminServiceOrder {
  const partial = order as Partial<AdminServiceOrder>
  return {
    ...order,
    user: partial.user ?? {
      id: 0,
      username: null,
      email: null,
      phone: null,
      nickname: null,
    },
    items_snapshot: Array.isArray(partial.items_snapshot) ? partial.items_snapshot : [],
    content: Array.isArray(partial.content) ? partial.content : [],
    instances: Array.isArray(partial.instances) ? partial.instances : [],
    point_rewards: Array.isArray(partial.point_rewards) ? partial.point_rewards : [],
    upstream_actions: Array.isArray(partial.upstream_actions) ? partial.upstream_actions : [],
    timeline: Array.isArray(partial.timeline) ? partial.timeline : [],
    refund_policy: {
      ...DEFAULT_REFUND_POLICY,
      ...(partial.refund_policy ?? {}),
    },
    resource_summary: {
      ...DEFAULT_RESOURCE_SUMMARY,
      ...(partial.resource_summary ?? {}),
    },
    refund: partial.refund ?? null,
  }
}

export async function listAdminServiceOrders(params: AdminServiceOrderFilters) {
  const p = new URLSearchParams()
  Object.entries(params).forEach(([key, value]) => {
    if (value !== undefined && value !== null && value !== "") p.set(key, String(value))
  })
  const { data } = await adminClient.get<ApiResponse<AdminServiceOrder[] | { items: AdminServiceOrder[]; total: number }>>(
    `/v1/admin/service-orders?${p.toString()}`,
  )
  return { ...data, data: listResult<AdminServiceOrder>(data.data).map(normalizeAdminServiceOrder) }
}

export async function getAdminServiceOrder(orderId: number) {
  const { data } = await adminClient.get<ApiResponse<AdminServiceOrder>>(
    `/v1/admin/service-orders/${orderId}`,
  )
  return { ...data, data: data.data ? normalizeAdminServiceOrder(data.data) : data.data }
}

export async function unsubscribeAdminServiceOrder(orderId: number) {
  const { data } = await adminClient.post<ApiResponse<AdminServiceOrderUnsubscribeResult>>(
    `/v1/admin/service-orders/${orderId}/unsubscribe`,
  )
  return data
}
