'use server'

import {ApiResponse, ExtraResp} from '@/lib/api'
import {callByUser} from './base'
import {listAnnouncements} from './announcement'

type statisticsResourceUsageReq = {
  resource_no?: string
  create_after?: Date
  create_before?: Date
}

type statisticsResourceUsageResp = {
  date: string
  count: number
}[]

export async function statisticsResourceUsage(props: statisticsResourceUsageReq) {
  return await callByUser<statisticsResourceUsageResp>('/api/resource/statistics/usage', props)
}

export async function statisticsResourceFree() {
  return await callByUser<{
    long: {
      resource_count: number
      resource_daily_free_sum: number
      resource_quota_sum: number
    }
    short: {
      resource_count: number
      resource_daily_free_sum: number
      resource_quota_sum: number
    }
  }>('/api/resource/statistics/free')
}

type listInitializationResp = {
  anno: ExtraResp<typeof listAnnouncements>
  free: ExtraResp<typeof statisticsResourceFree>
  usage: ExtraResp<typeof statisticsResourceUsage>
}
export async function listInitialization(): Promise<ApiResponse<listInitializationResp>> {
  const free = await statisticsResourceFree()
  if (!free.success) {
    return {
      success: false,
      status: 500,
      message: '套餐剩余数据获取失败',
    }
  }
  const anno = await listAnnouncements({
    page: 1,
    size: 5,
  })
  if (!anno.success) {
    return {
      success: false,
      status: 500,
      message: '公告数据获取失败',
    }
  }
  const usage = await statisticsResourceUsage({
    create_after: new Date(),
    create_before: new Date(),
  })
  if (!usage.success) {
    return {
      success: false,
      status: 500,
      message: '套餐用量数据获取失败',
    }
  }
  const data = {
    anno: anno.data,
    free: free.data,
    usage: usage.data,
  }

  return {
    success: true,
    data: data,
  }
}
