// reducers/historyReducer.ts
import { REHYDRATE } from 'redux-persist';
import {
  HISTORY_ADD,
  HISTORY_REMOVE,
  HISTORY_REMOVE_ALL,
} from '../actions/types';

// =======================
// Types
// =======================
export interface HistoryJob {
  id: number;
  title: string;
  data: Record<string, any>;
  url: string;
}

export interface HistoryState {
  jobs: HistoryJob[];
}

// =======================
// Action Types
// =======================
type HistoryAction =
  | { type: typeof REHYDRATE; payload?: { historyData?: HistoryState } }
  | { type: typeof HISTORY_ADD; payload: { title: string; data: Record<string, any>; url: string } }
  | { type: typeof HISTORY_REMOVE; payload: { id: number } }
  | { type: typeof HISTORY_REMOVE_ALL };

// =======================
// Initial State
// =======================
const initialState: HistoryState = {
  jobs: [],
};

// =======================
// Reducer
// =======================
export const historyData = (
  state: HistoryState = initialState,
  action: HistoryAction
): HistoryState => {
  switch (action.type) {
    case REHYDRATE:
      return action.payload?.historyData ?? state;

    case HISTORY_ADD: {
      try {
        const date = new Date();
        const oneDayAgo = date.getTime() - 24 * 60 * 60 * 1000;

        const newHistory: HistoryJob = {
          id: date.getTime(),
          title: action.payload.title,
          data: { ...action.payload.data },
          url: action.payload.url,
        };

        const recentHistory = state.jobs.filter((item) => item.id >= oneDayAgo);

        return { jobs: [...recentHistory, newHistory] };
      } catch (err) {
        console.error('Error parsing history data:', err);
        return state;
      }
    }

    case HISTORY_REMOVE:
      return {
        jobs: state.jobs.filter((item) => item.id !== action.payload.id),
      };

    case HISTORY_REMOVE_ALL:
      return { jobs: [] };

    default:
      return state;
  }
};
