import { NextRequest, NextResponse } from "next/server";
import { getSessionContext } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { sendInvoiceSchema } from "@/lib/validations/invoice";
import { sendInvoiceEmail } from "@/lib/resend";
import { formatCurrency, formatDate } from "@/lib/utils";

async function getOrganizationId(userId: string): Promise<string | null> {
  const membership = await prisma.organizationMember.findFirst({
    where: { userId, joinedAt: { not: null } },
    select: { organizationId: true },
    orderBy: { createdAt: "asc" },
  });
  return membership?.organizationId ?? null;
}

// ─── POST /api/invoices/[id]/send ─────────────────────────────

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const ctx = await getSessionContext();
  if (!ctx) return NextResponse.json({ success: false, error: "Non authentifié" }, { status: 401 });
  const { userId, orgId } = ctx;
  const organizationId = await getOrganizationId(userId);
  if (!organizationId) {
    return NextResponse.json({ success: false, error: "Aucune organisation trouvée" }, { status: 404 });
  }

  const { id } = await params;

  const invoice = await prisma.invoice.findFirst({
    where: { id, organizationId },
    include: {
      customer: true,
    },
  });

  if (!invoice) {
    return NextResponse.json({ success: false, error: "Facture introuvable" }, { status: 404 });
  }

  if (invoice.status === "PAID" || invoice.status === "CANCELED" || invoice.status === "REFUNDED") {
    return NextResponse.json(
      { success: false, error: `Impossible d'envoyer une facture au statut ${invoice.status}` },
      { status: 409 }
    );
  }

  const body = await request.json().catch(() => null);
  if (!body) {
    return NextResponse.json({ success: false, error: "Corps de requête invalide" }, { status: 400 });
  }

  const parsed = sendInvoiceSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json(
      { success: false, error: "Données invalides", details: parsed.error.flatten() },
      { status: 422 }
    );
  }

  const { recipientEmail, subject: _subject, message: _message, sendCopy } = parsed.data;

  const customerName = invoice.customer?.name ?? recipientEmail;
  const amountFormatted = formatCurrency(Number(invoice.total), invoice.currency);
  const dueDateFormatted = invoice.dueDate
    ? formatDate(invoice.dueDate)
    : "Non définie";

  // Envoi email principal
  await sendInvoiceEmail({
    to: recipientEmail,
    invoiceNumber: invoice.number,
    customerName,
    amount: amountFormatted,
    dueDate: dueDateFormatted,
    pdfUrl: invoice.pdfUrl ?? undefined,
  });

  // Copie à l'expéditeur si demandée
  if (sendCopy) {
    const sender = await prisma.user.findUnique({
      where: { id: userId },
      select: { email: true, name: true },
    });
    if (sender?.email && sender.email !== recipientEmail) {
      await sendInvoiceEmail({
        to: sender.email,
        invoiceNumber: invoice.number,
        customerName,
        amount: amountFormatted,
        dueDate: dueDateFormatted,
        pdfUrl: invoice.pdfUrl ?? undefined,
      });
    }
  }

  // Mise à jour du statut et de la date d'envoi
  const updated = await prisma.invoice.update({
    where: { id },
    data: {
      status: "SENT",
      sentAt: new Date(),
    },
    include: {
      customer: { select: { id: true, name: true, email: true } },
    },
  });

  return NextResponse.json({ success: true, data: updated });
}
