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

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;

  // Récupérer le nom de l'organisation
  const membership = await prisma.organizationMember.findFirst({
    where: { userId, joinedAt: { not: null } },
    include: { organization: { select: { name: true } } },
    orderBy: { createdAt: "asc" },
  });
  const orgName = membership?.organization.name ?? "";

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

  if (!quote) return NextResponse.json({ success: false, error: "Devis introuvable" }, { status: 404 });
  if (quote.status === "CONVERTED") return NextResponse.json({ success: false, error: "Devis déjà converti" }, { status: 409 });
  if (quote.status === "REJECTED" || quote.status === "EXPIRED") {
    return NextResponse.json({ success: false, error: `Impossible d'envoyer un devis ${quote.status}` }, { status: 409 });
  }

  const customerEmail = quote.customer?.email;
  if (customerEmail) {
    try {
      await sendQuoteEmail({
        to: customerEmail,
        quoteNumber: quote.number,
        customerName: quote.customer?.name ?? customerEmail,
        amount: formatCurrency(Number(quote.total), quote.currency),
        validUntil: quote.expiryDate ? formatDate(quote.expiryDate) : undefined,
        orgName,
        pdfUrl: `${process.env.NEXT_PUBLIC_APP_URL}/api/quotes/${id}/pdf`,
      });
    } catch (err) {
      console.error("[QUOTE_SEND] Email error:", err);
    }
  }

  const updated = await prisma.quote.update({
    where: { id },
    data: { status: "SENT", sentAt: new Date() },
    include: {
      customer: { select: { id: true, name: true, email: true } },
      items: { orderBy: { order: "asc" } },
    },
  });

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