action
export async function uploadImageAndCreateProperty(values: string, user: User) {
const { images, name, description, bedroomCount, bathroomCount, areaSizeInM2, priceInUSD, amenities, forSale, city, country, address, state, zipCode } = JSON.parse(values) as FormData;
const userProfile = await deductBalance(user, 5);
if (!userProfile) {
console.error('Failed to deduct balance');
return;
}
const slug = `${name.replace(/\s+/g, '-').toLowerCase()}-${Date.now()}`;
const imagesUrl = [];
for (const image of images) {
console.log('Uploading image:', image.name)
const { data: uploadData, error: uploadError } = await supabase.storage
.from('properties-images')
.upload(`images/${slug}/${image.name}`, image, {
cacheControl: '3600',
upsert: false
});
if (uploadError) {
console.error('Error uploading image:', uploadError);
return;
}
const imageUrl = await getPublicUrl(uploadData.path);
imagesUrl.push(imageUrl);
}
const locationId = await getOrCreateLocation(city, country, address, state, zipCode);
console.log(locationId)
const { data, error } = await supabase
.from('properties')
.insert([{
name,
description,
images: imagesUrl,
bedroomCount: parseInt(bedroomCount),
bathroomCount: parseInt(bathroomCount),
areaSizeInM2: parseFloat(areaSizeInM2),
priceInUSD: parseFloat(priceInUSD),
amenities,
forSale: forSale === 'on' ? true : false,
slug,
published: false,
location: locationId,
user_id: user.id
}]);
if (error) {
console.error('Error inserting data:', error);
return;
}
console.log('Property inserted:', data);
return data;
}