import axios from 'axios'

const http = axios.create({
  baseURL: process.env.VUE_APP_PYTHON_API,
  timeout: 300000
})

function uploadFileTo(url, file) {
  const form = new FormData()
  form.append('file', file)
  return http.post(url, form, {
    headers: { 'Content-Type': 'multipart/form-data' }
  }).then(({ data }) => data)
}

// 爆品分析相关 API
// 销售概览相关 API
export async function uploadSaleOverviewFile(file) {
  return uploadFileTo('/api/sale-overview/upload', file)
}

export async function analyzeSaleOverview() {
  const { data } = await http.post('/api/sale-overview/analyze')
  return data
}

export async function analyzeSaleOverviewWithFile(file) {
  const uploadResult = await uploadSaleOverviewFile(file)
  if (!uploadResult.success) {
    throw new Error(uploadResult.message || 'File upload failed')
  }

  return analyzeSaleOverview()
}

export async function getSaleOverviewResults() {
  const { data } = await http.get('/api/sale-overview/results')
  return data
}

// 销售趋势预测相关 API
export async function uploadSaleTrendFile(file) {
  return uploadFileTo('/api/sale-trend/upload', file)
}

export async function analyzeSaleTrend() {
  const { data } = await http.post('/api/sale-trend/analyze')
  return data
}

export async function analyzeSaleTrendWithFile(file) {
  const uploadResult = await uploadSaleTrendFile(file)
  if (!uploadResult.success) {
    throw new Error(uploadResult.message || 'File upload failed')
  }

  return analyzeSaleTrend()
}

export async function getSaleTrendResults() {
  const { data } = await http.get('/api/sale-trend/results')
  return data
}

export async function predictSalesTrend(params) {
  const { data } = await http.post('/api/sale-trend/predict', params)
  return data
}

// 促销效果分析相关 API
export async function uploadSaleEffectFile(file) {
  return uploadFileTo('/api/sale-effect/upload', file)
}

export async function analyzeSaleEffect() {
  const { data } = await http.post('/api/sale-effect/analyze')
  return data
}

export async function analyzeSaleEffectWithFile(file) {
  const uploadResult = await uploadSaleEffectFile(file)
  if (!uploadResult.success) {
    throw new Error(uploadResult.message || 'File upload failed')
  }

  return analyzeSaleEffect()
}

export async function getSaleEffectResults() {
  const { data } = await http.get('/api/sale-effect/results')
  return data
}
