<script>
import {ref} from "vue";
import {authenticatedRequest} from "@/components/session/authenticatedRequest.vue";
import { parseError } from "@/components/request/HandleGlobalError.vue";

// Cached vehicles
export const vehicles = ref([]);

export const getUsersVehicles = async () => {
  return await authenticatedRequest("/user/vehicles", "GET")
      .then(
          (response) => {
            vehicles.value = response.data.data;
          }
      )
      .catch(
          (error) => {
            parseError(error, 'addVehicleUser');
          }
      );
}

export const addVehicleUser = async (reg, type, reference = null) => {
  return await authenticatedRequest("/vehicles", "POST", {
    reg,
    type: parseInt(type),
    wash_subscription: false,
    ...(reference ? { reference } : {}),
  })
      .then(
          (response) => {
            const vehicle = response.data.data;
            vehicles.value.push(vehicle);
            return vehicle;
          }
      )
      .catch(
          (error) => {
            parseError(error, 'addVehicleUser');
            throw error;
          }
      );
}

</script>
