'use server'
import {callByDevice, callByUser} from '@/actions/base'
import {Resource} from '@/lib/models'
import {PageRecord} from '@/lib/api'

export type CreateResourceReq = {
  type: number
  short?: {
    live: number
    mode: number
    quota: number
    expire?: number
  }
  long?: {
    live: number
    mode: number
    quota: number
    expire?: number
  }
}

export async function listResourceShort(props: {
  page: number
  size: number
  resource_no?: string
  type?: number
  create_after?: Date
  create_before?: Date
  expire_after?: Date
  expire_before?: Date
}) {
  return await callByUser<PageRecord<Resource<1>>>('/api/resource/list/short', props)
}

export async function listResourceLong(props: {
  page: number
  size: number
  resource_no?: string
  type?: number
  create_after?: Date
  create_before?: Date
  expire_after?: Date
  expire_before?: Date
}) {
  return await callByUser<PageRecord<Resource<2>>>('/api/resource/list/long', props)
}

export async function allResource() {
  return callByUser<Resource<1 | 2>[]>('/api/resource/all')
}

export async function createResource(props: CreateResourceReq) {
  return await callByUser('/api/resource/create', props)
}

export async function prepareResource(props: {
  payment_method: number
  payment_platform: number
} & CreateResourceReq) {
  return await callByUser<{
    trade_no: string
    pay_url: string
  }>('/api/trade/create', {
    platform: props.payment_platform,
    method: props.payment_method,
    type: 1,
    resource: {
      type: props.type,
      short: props.short,
      long: props.long,
    },
  })
}

export async function completeResource(props: {
  trade_no: string
  method: number
}) {
  return callByUser('/api/trade/complete', props)
}

export async function payClose(props: {
  trade_no: string
  method: number
}) {
  return callByUser('/api/trade/cancel', props)
}

export async function getPrice(props: CreateResourceReq) {
  return callByDevice<{price: string}>('/api/resource/price', props)
}
