import { isThisWeek, isToday, isWithinInterval, subDays } from 'date-fns'
import type { Conversation } from '@/types/conversation'

export function processConversationData(records: Conversation[]): Conversation[] {
  const today = new Date()
  const thirtyDaysAgo = subDays(today, 30)

  const processedData: Conversation[] = []
  let hasToday = false
  let hasThisWeek = false
  let hasLast30Days = false
  let hasOlder = false

  records.forEach((item) => {
    const endDate = new Date(item.endTime)

    // 今天的数据
    if (isToday(endDate)) {
      if (!hasToday) {
        processedData.push({
          conversationId: '',
          conversationTitle: '今天',
          currentConversationFlag: false,
          endTime: '',
        } as any)
        hasToday = true
      }
      processedData.push({
        ...item,
      })
    }
    // 最近一周但不是今天的数据
    else if (isThisWeek(endDate, { weekStartsOn: 1 })) {
      if (!hasThisWeek) {
        processedData.push({
          conversationId: '',
          conversationTitle: '最近一周',
          currentConversationFlag: false,
          endTime: '',
        } as Conversation)
        hasThisWeek = true
      }
      processedData.push({
        ...item,
      })
    }
    // 最近30天但不是本周的数据
    else if (isWithinInterval(endDate, { start: thirtyDaysAgo, end: today })) {
      if (!hasLast30Days) {
        processedData.push({
          conversationId: '',
          conversationTitle: '最近30天',
          currentConversationFlag: false,
          endTime: '',
        } as Conversation)
        hasLast30Days = true
      }
      processedData.push({
        ...item,
      })
    }
    else {
      if (!hasOlder) {
        processedData.push({
          conversationId: '',
          conversationTitle: '更早',
          currentConversationFlag: false,
          endTime: '',
        } as Conversation)
        hasOlder = true
      }
      processedData.push({
        ...item,
      })
    }
  })

  return processedData
}
