// reducers/notificationReducer.ts
import { REHYDRATE } from 'redux-persist';
import {
    GET_NOTIFICATION_FAILED,
    GET_NOTIFICATION_REQUEST,
    GET_NOTIFICATION_SUCCESS,
} from '../actions/types';

// =======================
// Types
// =======================
export interface Notification {
  id: string | number;
  title: string;
  body?: string;
  read?: boolean;
  [key: string]: any;
}

export interface NotificationState {
  notifications: Notification[];
  total_count: number;
  read_count: number;
  unread_count: number;
  loading: boolean;
  error: Record<string, any>;
}

// =======================
// Action Types
// =======================
type NotificationAction =
  | { type: typeof REHYDRATE; payload?: { notificationData?: NotificationState } }
  | { type: typeof GET_NOTIFICATION_REQUEST }
  | { type: typeof GET_NOTIFICATION_SUCCESS; payload: { data: Notification[]; total_count: number; read_count: number; unread_count: number } }
  | { type: typeof GET_NOTIFICATION_FAILED; payload: Record<string, any> };

// =======================
// Initial State
// =======================
const initialState: NotificationState = {
  notifications: [],
  total_count: 0,
  read_count: 0,
  unread_count: 0,
  loading: false,
  error: {},
};

// =======================
// Reducer
// =======================
export const notificationData = (
  state: NotificationState = initialState,
  action: NotificationAction
): NotificationState => {
  switch (action.type) {
    case REHYDRATE:
      return action.payload?.notificationData
        ? {
            ...state,
            notifications: [...(action.payload.notificationData.notifications || [])],
            total_count: action.payload.notificationData.total_count || 0,
            read_count: action.payload.notificationData.read_count || 0,
            unread_count: action.payload.notificationData.unread_count || 0,
            loading: false,
            error: {},
          }
        : state;

    case GET_NOTIFICATION_REQUEST:
      return { ...state, loading: true, error: {} };

    case GET_NOTIFICATION_SUCCESS:
      return {
        ...state,
        notifications: [...(action.payload.data || [])],
        total_count: action.payload.total_count || 0,
        read_count: action.payload.read_count || 0,
        unread_count: action.payload.unread_count || 0,
        loading: false,
        error: {},
      };

    case GET_NOTIFICATION_FAILED:
      return { ...state, loading: false, error: action.payload || {} };

    default:
      return state;
  }
};
