import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import Cookies from "js-cookie";
import { POST } from "../../utils/api";
import { API } from "../../endpoints/common_endpoints";

// Utility function for API requests
const apiRequest = async (apiFn, api, data, errorMessage) => {
    try {
        const response = await apiFn(api, data);
        if (response?.success) {
            return response?.data;
        } else {
            throw new Error(response?.message || errorMessage);
        }
    } catch (error) {
        throw new Error(error.message || errorMessage);
    }
};

export const careerForm = createAsyncThunk(
    'website/career',
    async (data, { rejectWithValue }) => {
        try {


            console.log(data,"sss");
            const response = await POST(API.CAREER_FORM, data);
            if (response?.data?.token) {
                Cookies.set("gurukrupa_security", response?.data?.token);
                return response?.data?.token;
            }

            return rejectWithValue(response);
        } catch (error) {
            return rejectWithValue(error.message);
        }
    }
);


// Helper function to handle common async state transitions
const handleAsyncState = (state, action, isSignin = false) => {
    switch (action.type) {
        case 'pending':
            state.status = 'loading';
            break;
        case 'fulfilled':
            state.status = 'succeeded';
            if (isSignin) {
                state.token = action.payload;
                state.is_signin = true;
            }
            break;
        case 'rejected':
            state.status = 'failed';
            state.error = action.payload;
            if (isSignin) state.is_signin = false;
            break;
        default:
            return state;
    }
};


// Create the slice
const careerformSlice = createSlice({
    name: "careerform",
    initialState: {
        token: '',
        name: '',
        error: null,
        status: 'idle',
        is_signin: false,
    },
    reducers: {
        setIsSignedOut: (state) => {
            state.is_signin = false;
            state.token = '';
            state.name = '';
        },
    },
    extraReducers: (builder) => {
        builder
            .addCase(careerForm.pending, (state) => handleAsyncState(state, { type: 'pending' }))
            .addCase(careerForm.fulfilled, (state, action) => handleAsyncState(state, { type: 'fulfilled', payload: action.payload }))
            .addCase(careerForm.rejected, (state, action) => handleAsyncState(state, { type: 'rejected', payload: action.payload }))


    },
});

export const { setIsSignedOut } = careerformSlice.actions;

export default careerformSlice.reducer;