import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { User } from '@/types/user.types';

// Check if running in production mode
const isProduction = (): boolean => {
  try {
    return import.meta.env.PROD || import.meta.env.MODE === 'production';
  } catch {
    return false;
  }
};

// Safe localStorage access - returns null in production (cookies used instead)
const getStoredToken = (): string | null => {
  if (isProduction()) {
    return null; // In production, auth is via httpOnly cookies
  }
  try {
    return localStorage.getItem('token');
  } catch {
    return null;
  }
};

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

const initialState: AuthState = {
  user: null,
  token: getStoredToken(),
  isAuthenticated: false,
  isLoading: false,
  error: null,
};

const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    loginStart: (state) => {
      state.isLoading = true;
      state.error = null;
    },
    loginSuccess: (state, action: PayloadAction<{ user: User; token: string }>) => {
      state.isLoading = false;
      state.isAuthenticated = true;
      state.user = action.payload.user;
      state.token = action.payload.token;
      state.error = null;
      // Only store in localStorage in development mode
      if (!isProduction()) {
        try {
          localStorage.setItem('token', action.payload.token);
        } catch {
          // Ignore storage errors
        }
      }
    },
    loginFailure: (state, action: PayloadAction<string>) => {
      state.isLoading = false;
      state.isAuthenticated = false;
      state.user = null;
      state.token = null;
      state.error = action.payload;
      if (!isProduction()) {
        try {
          localStorage.removeItem('token');
        } catch {
          // Ignore storage errors
        }
      }
    },
    logout: (state) => {
      state.isAuthenticated = false;
      state.user = null;
      state.token = null;
      state.error = null;
      if (!isProduction()) {
        try {
          localStorage.removeItem('token');
        } catch {
          // Ignore storage errors
        }
      }
    },
    clearError: (state) => {
      state.error = null;
    },
    updateUser: (state, action: PayloadAction<User>) => {
      state.user = action.payload;
    },
  },
});

export const {
  loginStart,
  loginSuccess,
  loginFailure,
  logout,
  clearError,
  updateUser,
} = authSlice.actions;

export default authSlice;
