import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import { User } from '../../lib/mock-data';
import { API } from '../../api/API';

interface AuthState {
    user: User | null;
    token: string | null;
    isAuthenticated: boolean;
    loading: boolean;
    error: string | null;
}

const initialState: AuthState = {
    user: null,
    token: localStorage.getItem('token'),
    isAuthenticated: false,
    loading: true,
    error: null,
};

export const initializeAuth = createAsyncThunk(
    'auth/initializeAuth',
    async (_, { rejectWithValue }) => {
        const token = localStorage.getItem('token');
        if (!token) {
            return rejectWithValue('No token found');
        }

        try {
            const response = await API.getCurrentUser();
            if (response.ok && response.data) {
                const { user } = response.data as any;
                return {
                    user: {
                        id: user.id,
                        name: user.fullName || user.email.split('@')[0],
                        email: user.email,
                        password: '',
                        role: typeof user.role === 'string' ? user.role : (user.roleCode || 'User'),
                        roleCode: user.roleCode || (typeof user.role === 'string' ? user.role : 'User')
                    } as User,
                    token
                };
            }
            return rejectWithValue('Failed to fetch user');
        } catch (error: any) {
            return rejectWithValue(error.message || 'Session restoration failed');
        }
    }
);

const authSlice = createSlice({
    name: 'auth',
    initialState,
    reducers: {
        setCredentials: (
            state,
            action: PayloadAction<{ user: User; token: string }>
        ) => {
            state.user = action.payload.user;
            state.token = action.payload.token;
            state.isAuthenticated = true;
            state.loading = false;
            localStorage.setItem('token', action.payload.token);
        },
        logout: (state) => {
            state.user = null;
            state.token = null;
            state.isAuthenticated = false;
            state.loading = false;
            localStorage.removeItem('token');
        },
        setLoading: (state, action: PayloadAction<boolean>) => {
            state.loading = action.payload;
        },
    },
    extraReducers: (builder) => {
        builder
            .addCase(initializeAuth.pending, (state) => {
                state.loading = true;
            })
            .addCase(initializeAuth.fulfilled, (state, action) => {
                state.user = action.payload.user;
                state.token = action.payload.token;
                state.isAuthenticated = true;
                state.loading = false;
            })
            .addCase(initializeAuth.rejected, (state) => {
                state.user = null;
                state.token = null;
                state.isAuthenticated = false;
                state.loading = false;
                localStorage.removeItem('token');
            });
    },
});

export const { setCredentials, logout, setLoading } = authSlice.actions;

export default authSlice.reducer;
