import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit'
import { RootState } from '../../app/store';
import { shortenUrlApi } from '../../api/url/urlApi';
import { UrlState } from './types';

export const shortenUrl = createAsyncThunk(
    'url/shortenUrl',
    async (url: string) => {
        const baseUrl = process.env.REACT_APP_API_BASE_URL
        const data = await shortenUrlApi({ url });
        return `${baseUrl}/${data.shortcode}`;
    }
);

const initialState: UrlState = {
    shortUrl: '',
    status: 'idle',
    error: null,
};

const urlSlice = createSlice({
    name: 'url',
    initialState,
    reducers: {
        clearShortUrl(state) {
            state.shortUrl = '';
            state.status = 'idle';
            state.error = null;
        },
    },
    extraReducers: (builder) => {
        builder
            .addCase(shortenUrl.pending, (state) => {
                state.status = 'loading';
                state.shortUrl = '';
                state.error = null;
            })
            .addCase(shortenUrl.fulfilled, (state, action: PayloadAction<string>) => {
                state.status = 'succeeded';
                state.shortUrl = action.payload;
            })
            .addCase(shortenUrl.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.error.message || 'Something went wrong';
            });
    },
});

export const { clearShortUrl } = urlSlice.actions;
export const selectShortUrl = (state: RootState) => state.url.shortUrl;
export const selectUrlStatus = (state: RootState) => state.url.status;
export const selectUrlError = (state: RootState) => state.url.error;

export default urlSlice.reducer;