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

export interface SpendEventTypeConfig {
  id: number
  code: string
  label: string
  description: string | null
  enabled: boolean
  sort_order: number
  updated_at: string | null
}

export interface MemberLevel {
  id: number
  name: string
  level: number
  min_total_spent: number
  self_discount_rate: number
  points_multiplier: number
  max_points_discount_rate: number
  can_apply_agent: boolean
  sort_order: number
  enabled: boolean
}

export interface SpendEventTypeUpdateResult {
  config: SpendEventTypeConfig
  recalculated_users: number
}

export interface SpendRecalculateResult {
  recalculated_users: number
}

const BASE = "/v1/admin/membership"

export async function listMemberLevels() {
  const { data } = await adminClient.get<ApiResponse<MemberLevel[] | { items: MemberLevel[]; total: number }>>(`${BASE}/levels`)
  return { ...data, data: listResult<MemberLevel>(data.data) }
}

export async function listSpendEventTypes() {
  const { data } = await adminClient.get<ApiResponse<SpendEventTypeConfig[] | { items: SpendEventTypeConfig[]; total: number }>>(
    `${BASE}/spend-event-types`,
  )
  return { ...data, data: listResult<SpendEventTypeConfig>(data.data) }
}

export async function updateSpendEventType(code: string, enabled: boolean) {
  const { data } = await adminClient.patch<ApiResponse<SpendEventTypeUpdateResult>>(
    `${BASE}/spend-event-types/${code}`,
    { enabled },
  )
  return data
}

export async function recalculateSpend() {
  const { data } = await adminClient.post<ApiResponse<SpendRecalculateResult>>(
    `${BASE}/spend/recalculate`,
  )
  return data
}
