import { createSlice } from "@reduxjs/toolkit";
import { sellerLogin, buyerLogin } from "../api/api";

interface UserLogin {
    isLoggedIn: boolean;
    isLoading: boolean;
    success: boolean;
    message: string | null;
    error: string | null;
    userData: any | null;
}

const loginSliceSeller = createSlice({
    name: 'login',
    initialState: {
        isLoggedIn: false,
        isLoading: false,
        success: false,
        message: null,
        error: null,
        userData: null
    } as UserLogin,
    reducers: {
        updateLogoutState(state) {
            state.isLoggedIn = false;
            state.userData = null;
            state.error = null;
        },
    },
    extraReducers: (builder) => {
        builder
            .addCase(sellerLogin.pending, (state) => {
                state.isLoading = true;
                state.isLoggedIn = false;
                state.error = null;
                state.message = null;
            })
            .addCase(sellerLogin.fulfilled, (state, action) => {
                state.isLoading = false;
                state.isLoggedIn = action.payload.success;
                state.userData = action.payload;
                state.message = action.payload.message || '';
                state.error = action.payload.error || '';
            })
            .addCase(sellerLogin.rejected, (state, action) => {
                state.isLoading = false;
                state.isLoggedIn = false;
                state.error = action.error.message || 'Login failed';
                state.message = null;
            })
            .addCase(buyerLogin.pending, (state) => {
                state.isLoading = true;
                state.isLoggedIn = false;
                state.error = null;
                state.message = null;
            })
            .addCase(buyerLogin.fulfilled, (state, action) => {
                state.isLoading = false;
                state.isLoggedIn = action.payload.success;
                state.userData = action.payload;
                state.message = action.payload.message || '';
                state.error = action.payload.error || '';
            })
            .addCase(buyerLogin.rejected, (state, action) => {
                state.isLoading = false;
                state.isLoggedIn = false;
                state.error = action.error.message || 'Login failed';
                state.message = null;
            });
    }
});

export const { updateLogoutState } = loginSliceSeller.actions;
export default loginSliceSeller.reducer;
