import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { fetchUserQaRecordPage } from '@/api/conversation'
import type { ChatRecord, ChatState, OriginalRecord } from '@/types/chat'

const initialState: ChatState = {
  records: [],
  isLoading: false,
  error: null,
}

function processApiResponse(data: OriginalRecord[]): ChatRecord[] {
  const chatRecord: ChatRecord[] = []
  if (data.length === 0)
    return chatRecord
  data.forEach((record) => {
    chatRecord.push({
      type: 'question',
      originalData: record,
    })

    if (record.answerList && record.answerList.length > 0) {
      chatRecord.push({
        type: 'answer',
        originalData: record,
      })
    }
  })

  return chatRecord
}

export const fetchChatRecords = createAsyncThunk(
  'chat/fetchRecords',
  async (conversationId: string) => {
    const response = await fetchUserQaRecordPage(conversationId)
    return processApiResponse(response.data)
  },
)

const chatSlice = createSlice({
  name: 'chat',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchChatRecords.pending, (state) => {
        state.isLoading = true
        state.error = null
      })
      .addCase(fetchChatRecords.fulfilled, (state, action) => {
        state.isLoading = false
        state.records = action.payload
      })
      .addCase(fetchChatRecords.rejected, (state, action) => {
        state.isLoading = false
        state.error = action.error.message || 'Failed to fetch chat records'
      })
  },
})

export default chatSlice.reducer
