<script setup>
import { useApartmentStore } from '@/stores/apartments'

defineProps(['label'])

const apartments = useApartmentStore()

async function handleFileUpload(event) {
  try {
    const fileBlob = event.target.files
    const formData = new FormData()

    formData.append('image', fileBlob[0])

    const response = await apartments.uploadFile(apartments.active, formData)

    if (response.success) {
      await apartments.fetchFile(apartments.active, true)
    }
  } catch (error) {
    console.error('ERROR:', error.name)
  }
}
</script>

<template>
  <div class="file-upload button primary">
    <input type="file" @change="handleFileUpload" />
    <div class="file-upload__label">
      <span>{{ label }}</span>
    </div>
  </div>
</template>

<style scoped>
.file-upload {
  position: relative;
  display: flex;
}

.file-upload>input[type=file] {
  position: absolute;
  appearance: none;
  width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
}

.file-upload__label {
  pointer-events: none;
}
</style>