/**
 * API de Envio de Notificações
 * Chamada pelo Convex para enviar e-mails respeitando preferências do usuário
 */

import { NextRequest, NextResponse } from "next/server"
import { z } from "zod"

import { prisma } from "@/lib/prisma"
import { sendEmail, type NotificationType, type TemplateName, NOTIFICATION_TYPES } from "@/server/email"

// Token de autenticação interna (deve ser o mesmo usado no Convex)
const INTERNAL_TOKEN = process.env.INTERNAL_HEALTH_TOKEN ?? process.env.REPORTS_CRON_SECRET

const sendNotificationSchema = z.object({
  type: z.enum([
    "ticket_created",
    "ticket_assigned",
    "ticket_resolved",
    "ticket_reopened",
    "ticket_status_changed",
    "ticket_priority_changed",
    "comment_public",
    "comment_response",
    "sla_at_risk",
    "sla_breached",
    "automation",
  ]),
  to: z.object({
    email: z.string().email(),
    name: z.string().optional(),
    userId: z.string().optional(),
  }),
  subject: z.string(),
  data: z.record(z.any()),
  tenantId: z.string().optional(),
  skipPreferenceCheck: z.boolean().optional(),
})

async function shouldSendNotification(
  userId: string | undefined,
  notificationType: NotificationType | "automation",
  tenantId?: string
): Promise<boolean> {
  // Automações sempre passam (são configuradas separadamente)
  if (notificationType === "automation") return true

  // Se não tem userId, não pode verificar preferências
  if (!userId) return true

  try {
    const prefs = await prisma.notificationPreferences.findUnique({
      where: { userId },
    })

    // Se não tem preferências, usa os defaults
    if (!prefs) return true

    // Se e-mail está desabilitado globalmente
    if (!prefs.emailEnabled) return false

    // Verifica se é um tipo obrigatório
    const config = NOTIFICATION_TYPES[notificationType as NotificationType]
    if (config?.required) return true

    // Verifica preferências por tipo
    const typePrefs = prefs.typePreferences
      ? JSON.parse(prefs.typePreferences as string)
      : {}

    if (notificationType in typePrefs) {
      return typePrefs[notificationType] !== false
    }

    // Usa o default do tipo
    return config?.defaultEnabled ?? true
  } catch (error) {
    console.error("[notifications/send] Erro ao verificar preferências:", error)
    // Em caso de erro, envia a notificação
    return true
  }
}

function getTemplateForType(type: string): string {
  const templateMap: Record<string, string> = {
    ticket_created: "ticket_created",
    ticket_assigned: "ticket_assigned",
    ticket_resolved: "ticket_resolved",
    ticket_reopened: "ticket_status",
    ticket_status_changed: "ticket_status",
    ticket_priority_changed: "ticket_status",
    comment_public: "ticket_comment",
    comment_response: "ticket_comment",
    sla_at_risk: "sla_warning",
    sla_breached: "sla_breached",
    automation: "automation",
  }
  return templateMap[type] ?? "simple_notification"
}

export async function POST(request: NextRequest) {
  try {
    // Verifica autenticação
    const authHeader = request.headers.get("authorization")
    const token = authHeader?.replace("Bearer ", "")

    if (!INTERNAL_TOKEN || token !== INTERNAL_TOKEN) {
      return NextResponse.json({ error: "Não autorizado" }, { status: 401 })
    }

    const body = await request.json()
    const parsed = sendNotificationSchema.safeParse(body)

    if (!parsed.success) {
      return NextResponse.json(
        { error: "Dados inválidos", details: parsed.error.flatten() },
        { status: 400 }
      )
    }

    const { type, to, subject, data, tenantId, skipPreferenceCheck } = parsed.data

    // Verifica preferências do usuário
    if (!skipPreferenceCheck) {
      const shouldSend = await shouldSendNotification(
        to.userId,
        type as NotificationType | "automation",
        tenantId
      )

      if (!shouldSend) {
        return NextResponse.json({
          success: true,
          skipped: true,
          reason: "user_preference_disabled",
        })
      }
    }

    // Envia o e-mail
    const template = getTemplateForType(type)
    const result = await sendEmail({
      to: {
        email: to.email,
        name: to.name,
        userId: to.userId,
      },
      subject,
      template,
      data,
      notificationType: type === "automation" ? undefined : (type as NotificationType),
      tenantId,
      skipPreferenceCheck: true, // Já verificamos acima
    })

    return NextResponse.json({
      success: result.success,
      skipped: result.skipped,
      reason: result.reason,
    })
  } catch (error) {
    console.error("[notifications/send] Erro:", error)
    return NextResponse.json(
      { error: "Erro interno do servidor" },
      { status: 500 }
    )
  }
}
