import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import axios from "axios";
import {LoadingType} from "../../models/Types";

interface AuthState {
	state: LoadingType,
	authenticated: boolean;
	user?: User;
}

interface User {
	email: string;
	username: string;
}
interface LoginCredentials {
	username: string;
	password: string;
}

interface RegisterCredentials {
	username: string;
	email: string;
	password: string;
}

const initialState: AuthState = {
	state: "idle",
	authenticated: false,
	user: undefined,
}

export const logout = createAsyncThunk("auth/logout", async () => {
	await axios.get("/api/auth/logout");
})

export const login = createAsyncThunk("auth/login", async (credentials: LoginCredentials) => {
	const responce = await axios.post<User>("/api/auth/login", credentials);
	return responce.data;
})

export const register = createAsyncThunk("auth/register", async (credentials: RegisterCredentials) => {
	const responce = await axios.post<User>("/api/auth/register", credentials);
	return responce.data;
})

export const verify = createAsyncThunk("auth/verify", async () => {
	const responce = await axios.get<User>("/api/auth/verify");
	return responce.data;
});

const authSlice = createSlice({
	name: "auth",
	initialState,
	reducers: {
	},
	extraReducers: builder => {
		builder
			.addCase(logout.fulfilled, (state) => {
				state.authenticated = false;
				state.user = undefined;
			})
			.addCase(login.pending, (state) => {
				state.state = 'loading';
			})
			.addCase(login.fulfilled, (state, action) => {
				state.state = "idle";
				state.authenticated = true;
				state.user = action.payload;
			})
			.addCase(login.rejected, (state) => {
				state.state = "idle";
				state.authenticated = false;
				state.user = undefined;
			})
			.addCase(register.pending, (state) => {
				state.state = "loading";
			})
			.addCase(register.fulfilled, (state, action) => {
				state.state = "idle";
				state.authenticated = true;
				state.user = action.payload;
			})
			.addCase(verify.pending, (state) => {
				state.state = 'loading';
			})
			.addCase(verify.fulfilled, (state, action) => {
				state.state = "idle";
				state.authenticated = true;
				state.user = action.payload;
			})
			.addCase(verify.rejected, (state) => {
				state.state = "idle";
				state.authenticated = false;
				state.user = undefined;
			})
	}
})

export const { } = authSlice.actions;
export default authSlice.reducer;
