---
import AstroUtils from "libs/AstroUtils";
import type { RecordModel } from "pocketbase";


const pb = Astro.locals.pb

if(!pb.authStore.isValid){
		return Astro.redirect("/account")
}

await AstroUtils.wrap(async () => {
	if (Astro.request.method !== 'POST') {
		return
	}
  const poiJson = await Astro.request.json()

  const data = {Poi: poiJson.Poi, Poi_id:poiJson.Poi.id}

  let record: RecordModel

  try {
    record = await pb.collection('POI').create(data);
  } catch (error) {
    try{
      record = await pb.collection('POI').getFirstListItem(`Poi_id="${poiJson.Poi.id}"`)
    } catch (error2) {
      console.log("error 1 :")
      console.log(error)
      console.log("error 2 :")
      console.log(error2)
    }
  }

  try {
    if(poiJson.save){
        pb.collection('user_poi').create({owner: pb.authStore.model!.id, poi_list:record!.id})
      }else{
        record = await pb.collection('user_poi').getFirstListItem(`poi_list="${record!.id}"&&owner="${pb.authStore.model!.id}"`)
        pb.collection('user_poi').delete(record.id)
    }
  } catch (error) {
    console.log(error)
  }

})
---
