import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { fetchUserQaRecordPage } from '@/api/conversation'

interface Attachment {
  type: string
  name: string
  description: string
}

interface Answer {
  answer: string
  collectionFlag: boolean
  feedbackStatus: string
  groupId: string
  question: string
  recordId: string
  terminateFlag: boolean
  toolName: string
  attachmentList: Attachment[]
}

export interface ChatRecord {
  groupId: string
  question: string
  answerList: Answer[]
  productCode: string
  qaTime: string
}

interface ChatState {
  records: ChatRecord[]
  isLoading: boolean
  error: string | null
}

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

export const fetchChatRecords = createAsyncThunk(
  'chat/fetchRecords',
  async (conversationId: string) => {
    const response = await fetchUserQaRecordPage(conversationId)
    return 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
