import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { PaginationMeta } from '../common'
import { ChallengeAction } from '../challengeActions/challengeActionsSlice'

export interface Challenge {
  id: number
  title: string,
  description: string,
  reward: number,
}

export interface ChallengesState {
  challenges: Challenge[]
}

const initialState: ChallengesState = {
  challenges: []
}

export interface ChallengesPayload {
  data: (Challenge & { action: ChallengeAction | null })[]
  meta: PaginationMeta
}

export const challengesSlice = createSlice({
  name: 'challenges',
  initialState: initialState,
  reducers: {
    downloadChallenges(state, action: PayloadAction<ChallengesPayload>) {
      if (state.challenges)
        state.challenges = state.challenges.filter(challenge => action.payload.data.filter(dlChallenge => dlChallenge.id === challenge.id) === null)
      for (const dlChallenge of action.payload.data) {
        state.challenges.push({
          id: dlChallenge.id,
          title: dlChallenge.title,
          description: dlChallenge.description,
          reward: dlChallenge.reward,
        })
      }
      state.challenges.sort((c1, c2) => c2.id - c1.id)
    },
  },
})

export const { downloadChallenges } = challengesSlice.actions

export default challengesSlice.reducer