import { Models } from 'appwrite';
import { defineStore } from 'pinia';
import { AppwriteIds, databases } from 'src/boot/appwrite';
import { ref } from 'vue';

// const boatSource = null;

export interface Boat extends Models.Document {
  $id: string;
  name: string;
  displayName?: string;
  class?: string;
  year?: number;
  imgSrc?: string;
  iconSrc?: string;
  bookingAvailable: boolean;
  requiredCerts: string[];
  maxPassengers: number;
  defects: {
    type: string;
    severity: string;
    description: string;
    detail?: string;
  }[];
}

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 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 };
});
