import type { AlertPayload, AlertState } from "../../types/types";

export const initalState = {
  alertList: [],
  allAlerts: [],
};

export function reducer(state: AlertState, action: AlertPayload) {
  switch (action.type) {
    case "ADD": {
      if (action.payload && "vrm" in action.payload) {
        const alreadyExists = state.allAlerts.some(
          (alertItem) => alertItem.vrm === action.payload.vrm
        );
        if (alreadyExists) {
          return state;
        }
        return {
          ...state,
          allAlerts: [...state.allAlerts, action.payload],
          alertList: [...state.allAlerts, action.payload],
        };
      }
      return state;
    }

    case "SEARCH": {
      if (action.payload && typeof action.payload === "string") {
        const searchTerm = action.payload.toLowerCase();
        return {
          ...state,
          alertList: state.alertList.filter((alertItem) =>
            alertItem.vrm.toLowerCase().includes(searchTerm)
          ),
        };
      } else {
        return {
          ...state,
          alertList: state.allAlerts,
        };
      }
    }

    case "REMOVE": {
      return {
        ...state,
        alertList: state.alertList.filter(
          (alertItem) => alertItem.vrm !== action.payload.vrm
        ),
      };
    }

    case "DELETE": {
      return {
        ...state,
        alertList: action.payload,
      };
    }

    default:
      return { ...state };
  }
}
