/**
 * Inbox Store (Zustand) – stato messaggi e filtri.
 */

import { create } from 'zustand'
import type { MessageResponse } from '@/types/api.types'

interface InboxFilters {
  mailbox_id?: string
  direction?: 'inbound' | 'outbound'
  state?: string
  is_read?: boolean
  is_starred?: boolean
  search?: string
  page: number
  page_size: number
}

interface InboxState {
  messages: MessageResponse[]
  total: number
  filters: InboxFilters
  selectedMessageId: string | null
  unreadCount: number
  isLoading: boolean

  setFilters: (filters: Partial<InboxFilters>) => void
  resetFilters: () => void
  setMessages: (messages: MessageResponse[], total: number) => void
  prependMessage: (message: MessageResponse) => void
  updateMessage: (id: string, updates: Partial<MessageResponse>) => void
  selectMessage: (id: string | null) => void
  incrementUnread: () => void
  resetUnread: () => void
  setLoading: (loading: boolean) => void
}

const DEFAULT_FILTERS: InboxFilters = {
  page: 1,
  page_size: 50,
}

export const useInboxStore = create<InboxState>()((set) => ({
  messages: [],
  total: 0,
  filters: DEFAULT_FILTERS,
  selectedMessageId: null,
  unreadCount: 0,
  isLoading: false,

  setFilters: (filters) =>
    set((state) => ({
      filters: { ...state.filters, ...filters, page: 1 },
    })),

  resetFilters: () => set({ filters: DEFAULT_FILTERS }),

  setMessages: (messages, total) => set({ messages, total }),

  prependMessage: (message) =>
    set((state) => ({
      messages: [message, ...state.messages],
      total: state.total + 1,
      unreadCount: state.unreadCount + (message.is_read ? 0 : 1),
    })),

  updateMessage: (id, updates) =>
    set((state) => ({
      messages: state.messages.map((m) => (m.id === id ? { ...m, ...updates } : m)),
    })),

  selectMessage: (id) => set({ selectedMessageId: id }),

  incrementUnread: () => set((state) => ({ unreadCount: state.unreadCount + 1 })),

  resetUnread: () => set({ unreadCount: 0 }),

  setLoading: (loading) => set({ isLoading: loading }),
}))
