import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import http from "../../lib/https";
import { toast } from "sonner";

interface User {
	token: string | null;
	id: string;
	name: string;
	email: string;
	userType: string;
	phone: string;
}

interface AuthState {
	user: User | null;
	isAuthenticated: boolean;
	isLoading: boolean;
}

export const fetchAdminProfile = createAsyncThunk<
	User,
	void,
	{ rejectValue: string }
>("GetAdminProfile", async (_, { rejectWithValue }) => {
	try {
		const token = localStorage?.getItem("authToken");
		if (!token) throw new Error("No token found");

		const response = await http.get("/profile");

		if (!response.data?.data) throw new Error("Invalid API response");

		return response.data.data;
	} catch (error: any) {
		toast.error("Error Fetching Profile" + error);
		return rejectWithValue(
			error?.response?.data?.message || "An error occurred"
		);
	}
});

const initialState: AuthState = {
	user: null,
	isAuthenticated: false,
	isLoading: false,
};

const profileSlice = createSlice({
	name: "profile",
	initialState,
	reducers: {},
	extraReducers: (builder) => {
		builder
			.addCase(fetchAdminProfile.pending, (state) => {
				state.isLoading = true;
			})
			.addCase(fetchAdminProfile.fulfilled, (state, action) => {
				state.isLoading = false;
				state.user = action.payload;
				state.isAuthenticated = true;
			})
			.addCase(fetchAdminProfile.rejected, (state) => {
				state.isLoading = false;
			});
	},
});

export default profileSlice.reducer;
