// reducers/permissionsReducer.ts
import { REHYDRATE } from 'redux-persist';
import {
    PERMISSION_FAILED,
    PERMISSION_REQUEST,
    PERMISSION_SUCCESS,
} from '../actions/types';

// =======================
// Types
// =======================
export interface PermissionsState {
  permissions: Record<string, any>;
  loading: boolean;
  error: Record<string, any>;
}

// =======================
// Action Types
// =======================
type PermissionsAction =
  | { type: typeof REHYDRATE; payload?: { permissions?: PermissionsState } }
  | { type: typeof PERMISSION_REQUEST }
  | { type: typeof PERMISSION_SUCCESS; payload: { permissions_list: Record<string, any> } }
  | { type: typeof PERMISSION_FAILED; payload?: Record<string, any> };

// =======================
// Initial State
// =======================
const initialState: PermissionsState = {
  permissions: {},
  loading: false,
  error: {},
};

// =======================
// Reducer
// =======================
export const permissions = (
  state: PermissionsState = initialState,
  action: PermissionsAction
): PermissionsState => {
  switch (action.type) {
    case REHYDRATE:
      return action.payload?.permissions ?? state;

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

    case PERMISSION_SUCCESS:
      return {
        ...state,
        permissions: { ...(action.payload.permissions_list ?? {}) },
        loading: false,
        error: {},
      };

    case PERMISSION_FAILED:
      return {
        ...state,
        permissions: {},
        loading: false,
        error: action.payload ?? {},
      };

    default:
      return state;
  }
};
