"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 RemoteContentPrefsState = {
  trustedSenderEmails: string[]
  allowedMessageIds: string[]
}

type RemoteContentPrefsActions = {
  trustSender: (email: string) => void
  allowMessageRemoteContent: (messageId: string) => void
}

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

export function isMessageRemoteContentAllowed(
  allowedMessageIds: string[],
  messageId: string
): boolean {
  const id = messageId.trim()
  return id ? allowedMessageIds.includes(id) : false
}

export const useTrustedSendersStore = create<
  RemoteContentPrefsState & RemoteContentPrefsActions
>()(
  persist(
    (set, get) => ({
      trustedSenderEmails: [],
      allowedMessageIds: [],

      trustSender: (email) => {
        const norm = normalizeEmail(email)
        if (!norm || get().trustedSenderEmails.includes(norm)) return
        set((s) => ({
          trustedSenderEmails: [...s.trustedSenderEmails, norm],
        }))
      },

      allowMessageRemoteContent: (messageId) => {
        const id = messageId.trim()
        if (!id || get().allowedMessageIds.includes(id)) return
        set((s) => ({
          allowedMessageIds: [...s.allowedMessageIds, id],
        }))
      },
    }),
    {
      name: "ultimail-trusted-senders",
      storage: debouncedPersistJSONStorage,
    }
  )
)
