import axios, { AxiosError, AxiosResponse } from "axios";
import Toast from "react-native-toast-message";

import {
    PERMISSION_FAILED,
    PERMISSION_REQUEST,
    PERMISSION_SUCCESS,
} from "./types";

import { AnyAction } from "redux";
import { ThunkAction, ThunkDispatch } from "redux-thunk";
import config from '../../config/config';
import { RootState } from "../store";

type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType,
  RootState,
  unknown,
  AnyAction
>;

// API Response type
type PermissionsResponse = {
  [key: string]: any; // adjust if you know the structure
};

/**
 * ✅ Fetch Permissions
 */
export const getPermissions = (): AppThunk<Promise<void>> => {
  return async (dispatch: ThunkDispatch<RootState, unknown, AnyAction>) => {
    dispatch({ type: PERMISSION_REQUEST });

    try {
      const res: AxiosResponse<PermissionsResponse> = await axios.get(
        `${config.apiserver}/api/v1/enterprise_management/initial-data-fetch`
      );

      if (res?.data) {
        dispatch({
          type: PERMISSION_SUCCESS,
          payload: res.data,
        });
      } else {
        Toast.show({
          type: "error",
          text1: "Error",
          text2:
            "Something went wrong while fetching Permissions data. Please try again...",
          position: "top",
          visibilityTime: 4000,
        });

        dispatch({
          type: PERMISSION_FAILED,
          payload: "No permissions data returned from server",
        });
      }
    } catch (error) {
      const err = error as AxiosError;

      // Optional: handle 401 specifically
      if (err.response?.status === 401) {
        console.warn("Unauthorized request for permissions");
        // maybe handle token refresh here
      } else {
        console.error("Permission request error:", err);
        dispatch({
          type: PERMISSION_FAILED,
          payload: err,
        });
      }
    }
  };
};
