// reducers/questionReducer.ts
import { REHYDRATE } from "redux-persist";
import {
    DRAFT_ANSWERS,
    REMOVE_ALL_DRAFT_ANSWERS,
    REMOVE_DRAFT_ANSWERS,
} from "../actions/types";

// =======================
// Types
// =======================
export interface DraftAnswer {
  formId: string | number;
  selectedEntity: string;
  [key: string]: any;
}

export type DraftAnswerState = DraftAnswer[];

// Action types
type DraftAnswerAction =
  | { type: typeof REHYDRATE; payload?: { draftAnswerData?: DraftAnswerState } }
  | { type: typeof DRAFT_ANSWERS; payload: DraftAnswer[] }
  | { type: typeof REMOVE_DRAFT_ANSWERS; payload: { formId: string | number; selectedEntity: string } }
  | { type: typeof REMOVE_ALL_DRAFT_ANSWERS };

// =======================
// Initial State
// =======================
const initialState: DraftAnswerState = [];

// =======================
// Reducer
// =======================
export const draftAnswerData = (
  state: DraftAnswerState = initialState,
  action: DraftAnswerAction
): DraftAnswerState => {
  switch (action.type) {
    case REHYDRATE:
      return action.payload?.draftAnswerData ?? initialState;

    case DRAFT_ANSWERS: {
      const newDrafts = action.payload;
      const filteredState = state.filter(
        (item) =>
          !newDrafts.some(
            (draft) =>
              draft.formId === item.formId &&
              draft.selectedEntity === item.selectedEntity
          )
      );
      return [...filteredState, ...newDrafts];
    }

    case REMOVE_DRAFT_ANSWERS: {
      const { formId, selectedEntity } = action.payload;
      return state.filter(
        (item) =>
          !(item.formId === formId && item.selectedEntity === selectedEntity)
      );
    }

    case REMOVE_ALL_DRAFT_ANSWERS:
      return [];

    default:
      return state;
  }
};
