'use client'

import { create } from 'zustand'
import type { Identity } from '@/lib/compose-context'

type ComposeIdentitiesState = {
  identities: Identity[]
  hydrated: boolean
}

type ComposeIdentitiesActions = {
  hydrateFromApi: (identities: Identity[]) => void
  clear: () => void
}

export const useComposeIdentitiesStore = create<
  ComposeIdentitiesState & ComposeIdentitiesActions
>()((set) => ({
  identities: [],
  hydrated: false,
  hydrateFromApi: (identities) => set({ identities, hydrated: true }),
  clear: () => set({ identities: [], hydrated: false }),
}))

export function getComposeIdentities(): Identity[] {
  return useComposeIdentitiesStore.getState().identities
}

export function getDefaultComposeIdentity(accountId?: string | null): Identity | null {
  const identities = getComposeIdentities()
  if (identities.length === 0) return null
  if (accountId) {
    const scoped = identities.filter((i) => i.accountId === accountId)
    return scoped.find((i) => i.isDefault) ?? scoped[0] ?? null
  }
  return identities.find((i) => i.isDefault) ?? identities[0] ?? null
}
