"use client"

import { create } from "zustand"
import { persist } from "zustand/middleware"
import { normalizeEmail } from "@/lib/contacts/find-contact"
import { debouncedPersistJSONStorage } from "@/lib/stores/debounced-json-storage"

type BlockedSendersState = {
  blockedSenderEmails: string[]
}

type BlockedSendersActions = {
  blockSenders: (emails: string[]) => void
  unblockSender: (email: string) => void
}

export function isBlockedSenderEmail(
  blockedSenderEmails: string[],
  email: string,
): boolean {
  const norm = normalizeEmail(email)
  return norm ? blockedSenderEmails.includes(norm) : false
}

export const useBlockedSendersStore = create<
  BlockedSendersState & BlockedSendersActions
>()(
  persist(
    (set, get) => ({
      blockedSenderEmails: [],

      blockSenders: (emails) => {
        const next = new Set(get().blockedSenderEmails)
        for (const email of emails) {
          const norm = normalizeEmail(email)
          if (norm) next.add(norm)
        }
        set({ blockedSenderEmails: [...next] })
      },

      unblockSender: (email) => {
        const norm = normalizeEmail(email)
        if (!norm) return
        set((s) => ({
          blockedSenderEmails: s.blockedSenderEmails.filter((e) => e !== norm),
        }))
      },
    }),
    {
      name: "ultimail-blocked-senders",
      storage: debouncedPersistJSONStorage,
    },
  ),
)
