// src/store/userSlice.ts

import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import api from "../services/axiosClient";
import { BASE_URL } from "@/constants/config";

interface Vehicle {
  vehicle_id: number;
  model: string;
  chasis_number: string;
}

interface UserData {
  user_id: number;
  name: string;
  mobile: string;
  email: string | null;
  profile_url: string | null;
  vehicles: Vehicle[];
}

interface UserState {
  data: UserData | null;
  loading: boolean;
  error: string | null;
}

const initialState: UserState = {
  data: null,
  loading: false,
  error: null,
};

// 🔁 Thunk to get user details
export const getUserDetails = createAsyncThunk<UserData>(
  "user/getUserDetails",
  async (_, { rejectWithValue }) => {
    try {
      const response = await api.get(`${BASE_URL}/api/v1/get-user-details`);
      if (response.data.success) {
        return response.data.data;
      } else {
        return rejectWithValue("Failed to fetch user data");
      }
    } catch (error: any) {
      const message =
        error.response?.data?.message ||
        error.message ||
        "Something went wrong";
      return rejectWithValue(message);
    }
  }
);

const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    clearUser: (state) => {
      state.data = null;
      state.error = null;
      state.loading = false;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(getUserDetails.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        getUserDetails.fulfilled,
        (state, action: PayloadAction<UserData>) => {
          state.loading = false;
          state.data = action.payload;
        }
      )
      .addCase(getUserDetails.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  },
});

export const { clearUser } = userSlice.actions;
export default userSlice.reducer;
