/**
 * Mailbox Store (Zustand) – lista caselle PEC.
 */

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

interface MailboxState {
  mailboxes: MailboxResponse[]
  selectedMailboxId: string | null
  isLoading: boolean

  setMailboxes: (mailboxes: MailboxResponse[]) => void
  upsertMailbox: (mailbox: MailboxResponse) => void
  removeMailbox: (id: string) => void
  selectMailbox: (id: string | null) => void
  updateMailboxStatus: (id: string, status: string, errorMsg?: string) => void
  setLoading: (loading: boolean) => void
}

export const useMailboxStore = create<MailboxState>()((set) => ({
  mailboxes: [],
  selectedMailboxId: null,
  isLoading: false,

  setMailboxes: (mailboxes) => set({ mailboxes }),

  upsertMailbox: (mailbox) =>
    set((state) => {
      const idx = state.mailboxes.findIndex((m) => m.id === mailbox.id)
      if (idx >= 0) {
        const updated = [...state.mailboxes]
        updated[idx] = mailbox
        return { mailboxes: updated }
      }
      return { mailboxes: [...state.mailboxes, mailbox] }
    }),

  removeMailbox: (id) =>
    set((state) => ({
      mailboxes: state.mailboxes.filter((m) => m.id !== id),
    })),

  selectMailbox: (id) => set({ selectedMailboxId: id }),

  updateMailboxStatus: (id, status, errorMsg) =>
    set((state) => ({
      mailboxes: state.mailboxes.map((m) =>
        m.id === id
          ? {
              ...m,
              status: status as MailboxResponse['status'],
              sync_error_msg: errorMsg ?? m.sync_error_msg,
            }
          : m,
      ),
    })),

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