'use client'

import type { ApiIdentity, ApiMailSignature } from '@/lib/api/types'
import type { Identity } from '@/lib/compose-context'
import { insertSignatureHtml } from '@/components/gmail/compose/compose-shared'
import { getSignatureHtmlById } from '@/lib/stores/mail-signatures-store'

export function resolveIdentitySignatureHtml(
  identity: ApiIdentity,
  signaturesById?: Map<string, ApiMailSignature>
): string | null {
  const fromLibrary = identity.default_signature_id
    ? (signaturesById?.get(identity.default_signature_id)?.html ??
        getSignatureHtmlById(identity.default_signature_id))
    : null
  if (fromLibrary?.trim()) return fromLibrary
  const inline = identity.signature_html?.trim()
  return inline || null
}

export function apiIdentityToCompose(
  identity: ApiIdentity,
  signaturesById?: Map<string, ApiMailSignature>
): Identity {
  const defaultSignatureId = identity.default_signature_id ?? null
  const signatureHtml = resolveIdentitySignatureHtml(identity, signaturesById)
  return {
    id: identity.id,
    accountId: identity.account_id,
    name: identity.name,
    email: identity.email,
    defaultSignatureId,
    signatureHtml,
    isDefault: identity.is_default,
  }
}

export function buildBodyWithSignature(bodyHtml: string, identity: Identity): string {
  const html = identity.signatureHtml ?? null
  if (!html?.trim()) return bodyHtml
  return insertSignatureHtml(bodyHtml, html)
}

export function myEmailsFromIdentities(identities: Identity[]): Set<string> {
  return new Set(identities.map((i) => i.email.trim().toLowerCase()).filter(Boolean))
}

export function defaultComposeIdentity(
  identities: Identity[],
  accountId?: string | null
): Identity | 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
}

function composeIdentityDedupeKey(identity: Identity): string {
  return `${identity.accountId ?? ""}:${identity.email.trim().toLowerCase()}`
}

/** Évite les doublons accountId+email (hydratation multi-comptes / re-fetch). */
export function dedupeComposeIdentities(identities: Identity[]): Identity[] {
  const seen = new Set<string>()
  const out: Identity[] = []
  for (const identity of identities) {
    const key = composeIdentityDedupeKey(identity)
    if (seen.has(key)) continue
    seen.add(key)
    out.push(identity)
  }
  return out
}
