/**
 * 生命事件服务
 * 处理生命事件的增删改查
 */

import { get, post, put, del } from './request.js'

export const getEventList = async () => {
  const response = await get('/lifeEvent/list')
  return response
}

export const getEventPage = async ({ pageNum = 1, pageSize = 10 }) => {
  const response = await get('/lifeEvent/page', { pageNum, pageSize })
  return response
}

export const getEventById = async (id) => {
  const response = await get('/lifeEvent/detail', { id })
  return response
}

export const createEvent = async (eventData) => {
  const requestData = transformToBackendFormat(eventData)
  const response = await post('/lifeEvent/create', requestData)
  return response
}

export const updateEvent = async (eventData) => {
  const requestData = transformToBackendFormat(eventData)
  const response = await put('/lifeEvent/update', requestData)
  return response
}

export const deleteEvent = async (id) => {
  const response = await del('/lifeEvent/delete', { id })
  return response
}

const transformToBackendFormat = (frontendData) => {
  const {
    id,
    title,
    time,
    content,
    aiFeedback,
    eventType = 'daily_log',
    emotionType,
    emotionScore,
    tags
  } = frontendData

  return {
    id,
    title,
    eventDate: time,
    content,
    aiReply: aiFeedback,
    eventType,
    emotionType,
    emotionScore,
    tags
  }
}

export const transformToFrontendFormat = (backendData) => {
  if (!backendData) return null

  const {
    id,
    userId,
    title,
    eventDate,
    content,
    aiReply,
    eventType,
    emotionType,
    emotionScore,
    tags,
    createTime
  } = backendData

  return {
    id,
    userId,
    title: title || '',
    time: eventDate ? eventDate.split('T')[0] : '',
    content: content || '',
    aiFeedback: aiReply || '',
    eventType: eventType || 'daily_log',
    emotionType,
    emotionScore,
    tags: tags || [],
    createTime
  }
}

export const transformListToFrontend = (backendList) => {
  if (!Array.isArray(backendList)) return []
  return backendList.map(transformToFrontendFormat)
}

export default {
  getEventList,
  getEventPage,
  getEventById,
  createEvent,
  updateEvent,
  deleteEvent,
  transformToFrontendFormat,
  transformListToFrontend
}
