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

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

    if (isToday(endDate)) {
      if (!hasToday) {
        processedData.push({
          conversationId: '',
          conversationTitle: '今天',
          currentConversationFlag: false,
          endTime: '',
        } as any)
        hasToday = true
      }
      timeLabel = '今天'
    }
    else if (isThisWeek(endDate, { weekStartsOn: 1 })) {
      if (!hasThisWeek) {
        processedData.push({
          conversationId: '',
          conversationTitle: '最近一周',
          currentConversationFlag: false,
          endTime: '',
        } as Conversation)
        hasThisWeek = true
      }
      timeLabel = '最近一周'
    }
    else if (isWithinInterval(endDate, { start: thirtyDaysAgo, end: today })) {
      if (!hasLast30Days) {
        processedData.push({
          conversationId: '',
          conversationTitle: '最近30天',
          currentConversationFlag: false,
          endTime: '',
        } as Conversation)
        hasLast30Days = true
      }
      // eslint-disable-next-line unused-imports/no-unused-vars
      timeLabel = '最近30天'
    }
    else {
      return
    }

    processedData.push({
      ...item,
    })
  })

  return processedData
}
