import { MockupNeedProvider } from '../provider/MockupNeedProvider'
import type { NeedFilters } from '../provider/INeedProvider'
import type { Need, CreateNeedInput, UpdateNeedInput } from '../domain/need'
import type { ListResponse, ItemResponse } from './types'
import { throwServiceError } from './errors'
import { useSessionStore } from '../stores/sessionStore'

const provider = MockupNeedProvider

export const needService = {
  async getAll(filters?: NeedFilters): Promise<ListResponse<Need>> {
    try {
      const data = await provider.getAll(filters)
      return { data, meta: { total: data.length, page: 1, pageSize: data.length, hasMore: false } }
    } catch (err) {
      throwServiceError(err)
    }
  },
  async getById(id: string): Promise<ItemResponse<Need | null>> {
    try {
      const data = await provider.getById(id)
      return { data }
    } catch (err) {
      throwServiceError(err)
    }
  },
  async create(input: CreateNeedInput): Promise<ItemResponse<Need>> {
    try {
      // Neues Suchprofil der Organisation des Erstellers zuordnen (sonst fällt es aus der
      // org-gefilterten Liste — Aktive-Suche-Leiste zeigt sonst ein fremdes Profil)
      const orgId = useSessionStore.getState().currentUser?.organizationId
      const data = await provider.create({ ...input, organizationId: input.organizationId ?? orgId })
      return { data }
    } catch (err) {
      throwServiceError(err)
    }
  },
  async update(id: string, input: UpdateNeedInput): Promise<ItemResponse<Need>> {
    try {
      const data = await provider.update(id, input)
      return { data }
    } catch (err) {
      throwServiceError(err)
    }
  },
  async remove(id: string): Promise<ItemResponse<void>> {
    try {
      await provider.remove(id)
      return { data: undefined }
    } catch (err) {
      throwServiceError(err)
    }
  },
}
