import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import endpoints from '../../config/apiEndpoints';

// Define the Job interface
interface Job {
    encrypted_id: string;
    job_title: string;
    job_type: string;
    responsibilities: string;
}

// Define the state structure
interface JobState {
    jobs: Job[];
    loading: boolean;
    error: string | null;
    openJobId: string | null;
}

// Initial state
const initialState: JobState = {
    jobs: [],
    loading: false,
    error: null,
    openJobId: null
};
const {jobs: jobsApi} = endpoints;

// Async thunk for fetching jobs
export const fetchJobs = createAsyncThunk(
    'job/fetchJobs',
    async (_, { rejectWithValue }) => {
        try {
            const response = await fetch(jobsApi, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
            });
            
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            
            const data = await response.json();
            return data.data;
        } catch (error) {
            console.error('Error fetching jobs:', error);
            return rejectWithValue((error as Error).message);
        }
    }
);

// Create the job slice
const jobSlice = createSlice({
    name: 'job',
    initialState,
    reducers: {
        toggleJob: (state, action: PayloadAction<string>) => {
            state.openJobId = state.openJobId === action.payload ? null : action.payload;
        },
        clearJobs: (state) => {
            state.jobs = [];
        }
    },
    extraReducers: (builder) => {
        builder
            .addCase(fetchJobs.pending, (state) => {
                state.loading = true;
                state.error = null;
            })
            .addCase(fetchJobs.fulfilled, (state, action: PayloadAction<Job[]>) => {
                state.loading = false;
                state.jobs = action.payload;
            })
            .addCase(fetchJobs.rejected, (state, action) => {
                state.loading = false;
                state.error = action.payload as string;
            });
    }
});

// Export actions and reducer
export const { toggleJob, clearJobs } = jobSlice.actions;
export default jobSlice.reducer;