import client from "./client"
import type { ApiResponse } from "../types"

export interface CartProductSummary {
  id: number
  sku: string
  name: string
  status: string
  vcpu: number | null
  memory: string | null
  disk: string | null
  bandwidth: string | null
  stock_policy: string
  stock: number
  min_quantity: number
  max_quantity: number
  group_id: number
}

export interface CartItem {
  id: number
  user_id: number
  product_id: number
  cycle: string
  quantity: number
  auto_renew: boolean
  alias: string | null
  os_image: string | null
  unit_price: number
  addon_price: number
  setup_fee: number
  slider_values: Record<string, unknown> | null
  created_at: string
  updated_at: string
  product: CartProductSummary | null
}

export interface CartItemCreatePayload {
  product_id: number
  cycle: string
  quantity?: number
  auto_renew?: boolean
  alias?: string | null
  os_image?: string | null
  unit_price: number
  addon_price?: number
  setup_fee?: number
  slider_values?: Record<string, unknown> | null
}

export interface CartItemUpdatePayload {
  quantity?: number
  auto_renew?: boolean
  alias?: string | null
}

const BASE = "/v1/cart"

export async function listCartItems() {
  const { data } = await client.get<ApiResponse<CartItem[]>>(BASE)
  return data
}

export async function addCartItem(payload: CartItemCreatePayload) {
  const { data } = await client.post<ApiResponse<CartItem>>(BASE, payload)
  return data
}

export async function updateCartItem(id: number, payload: CartItemUpdatePayload) {
  const { data } = await client.patch<ApiResponse<CartItem>>(`${BASE}/${id}`, payload)
  return data
}

export async function deleteCartItem(id: number) {
  const { data } = await client.delete<ApiResponse<null>>(`${BASE}/${id}`)
  return data
}

export async function clearCart() {
  const { data } = await client.delete<ApiResponse<{ deleted: number }>>(BASE)
  return data
}
