import { defineStore } from 'pinia';
import { AppwriteIds, databases } from '~/utils/appwrite';
import { ref } from 'vue';
import type { Boat } from '~/utils/boat.types';

export { type Boat } from '~/utils/boat.types';

export const useBoatStore = defineStore('boat', () => {
  const boats = ref<Boat[]>([]);

  async function fetchBoats() {
    try {
      const response = await databases.listDocuments(
        AppwriteIds.databaseId,
        AppwriteIds.collection.boat
      );
      boats.value = response.documents as unknown as Boat[];
    } catch (error) {
      console.error('Failed to fetch boats', error);
    }
  }

  const getBoatById = (id: string | null | undefined): Boat | null => {
    if (!id) return null;
    return boats.value?.find((b) => b.$id === id) || null;
  };

  return { boats, fetchBoats, getBoatById };
});
