import { createSlice, PayloadAction, Action } from '@reduxjs/toolkit';
import { REHYDRATE } from 'redux-persist';
import type { User } from '@/types/user.types';

interface AuthState {
  user: User | null;
  token: string | null;
  refreshToken: string | null;
  isAuthenticated: boolean;
  permissions: string[];
  loading: boolean;
}

interface RehydrateAction extends Action<typeof REHYDRATE> {
  payload?: {
    auth?: AuthState;
  };
}

const initialState: AuthState = {
  user: null,
  token: null,
  refreshToken: null,
  isAuthenticated: false,
  permissions: [],
  loading: true,
};

const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    setCredentials: (
      state,
      action: PayloadAction<{ user: User; token: string; refreshToken?: string; permissions?: string[] }>
    ) => {
      state.user = action.payload.user;
      state.token = action.payload.token;
      state.refreshToken = action.payload.refreshToken || null;
      state.permissions = action.payload.permissions || [];
      state.isAuthenticated = true;
      state.loading = false;
    },
    logout: (state) => {
      state.user = null;
      state.token = null;
      state.refreshToken = null;
      state.permissions = [];
      state.isAuthenticated = false;
      state.loading = false;
    },
    setLoading: (state, action: PayloadAction<boolean>) => {
      state.loading = action.payload;
    },
    updateUser: (state, action: PayloadAction<Partial<User>>) => {
      if (state.user) {
        state.user = { ...state.user, ...action.payload };
      }
    },
  },
  extraReducers: (builder) => {
    builder.addMatcher(
      (action): action is RehydrateAction => action.type === REHYDRATE,
      (state, action) => {
        if (action.payload?.auth) {
          const rehydratedAuth = action.payload.auth;
          state.user = rehydratedAuth.user;
          state.token = rehydratedAuth.token;
          state.refreshToken = rehydratedAuth.refreshToken;
          state.permissions = rehydratedAuth.permissions;
          state.isAuthenticated = rehydratedAuth.isAuthenticated;
        }
        state.loading = false;
      }
    );
  },
});

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