import type { Organization } from '~/shared/types/pocketbase'

export const useOrg = defineStore('org', {
  state: () => ({
    org: null as Organization | null,
    loading: false,
  }),

  getters: {
    plan: (state) => state.org?.plan ?? 'free',
    orgId: (state) => state.org?.id ?? null,
  },

  actions: {
    async fetchOrg(orgId: string) {
      const { pb } = usePocketBase()
      this.loading = true
      try {
        this.org = await pb.collection('organizations').getOne(orgId) as unknown as Organization
      } catch (err) {
        console.error('Failed to fetch org', err)
      } finally {
        this.loading = false
      }
    },

    async updateOrg(data: Partial<Organization>) {
      if (!this.org) return
      const { pb } = usePocketBase()
      this.org = await pb.collection('organizations').update(this.org.id, data) as unknown as Organization
    },

    clearOrg() {
      this.org = null
    }
  }
})
