import { NextRequest, NextResponse } from "next/server";
import { getSessionContext } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { z } from "zod";
import { Prisma } from "@prisma/client";

// ─── Schemas ───────────────────────────────────────────────────

const quoteItemSchema = z.object({
  description: z.string().min(1, "Description requise"),
  quantity: z.coerce.number().positive("La quantité doit être positive"),
  unitPrice: z.coerce.number().min(0, "Le prix doit être positif ou nul"),
  taxRate: z.coerce.number().min(0).max(100),
  discount: z.coerce.number().min(0).max(100).optional().default(0),
  order: z.number().int().optional().default(0),
});

const updateQuoteSchema = z
  .object({
    customerId: z.string().optional(),
    subject: z.string().optional(),
    issueDate: z.string().or(z.date()).optional(),
    expiryDate: z.string().or(z.date()).optional(),
    currency: z.string().optional(),
    notes: z.string().optional(),
    terms: z.string().optional(),
    reference: z.string().optional(),
    items: z.array(quoteItemSchema).min(1).optional(),
  })
  .strict();

// ─── Helpers ───────────────────────────────────────────────────

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;
}

function round2(n: number): number {
  return Math.round(n * 100) / 100;
}

function calcItemTotals(item: {
  quantity: number;
  unitPrice: number;
  discount: number;
  taxRate: number;
}) {
  const baseAmount = item.quantity * item.unitPrice * (1 - item.discount / 100);
  const taxAmount = baseAmount * (item.taxRate / 100);
  const total = baseAmount + taxAmount;
  return {
    baseAmount: round2(baseAmount),
    taxAmount: round2(taxAmount),
    total: round2(total),
  };
}

// ─── GET /api/quotes/[id] ──────────────────────────────────────

export async function GET(
  _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 quote = await prisma.quote.findFirst({
    where: { id, organizationId },
    include: {
      customer: true,
      items: { orderBy: { order: "asc" } },
    },
  });

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

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

// ─── PATCH /api/quotes/[id] ────────────────────────────────────

export async function PATCH(
  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 existing = await prisma.quote.findFirst({
    where: { id, organizationId },
  });

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

  if (existing.status === "CONVERTED") {
    return NextResponse.json(
      { success: false, error: "Un devis converti en facture ne peut pas être modifié" },
      { 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 = updateQuoteSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json(
      { success: false, error: "Données invalides", details: parsed.error.flatten() },
      { status: 422 }
    );
  }

  const data = parsed.data;

  if (data.customerId) {
    const customer = await prisma.customer.findFirst({
      where: { id: data.customerId, organizationId },
    });
    if (!customer) {
      return NextResponse.json(
        { success: false, error: "Client introuvable dans cette organisation" },
        { status: 404 }
      );
    }
  }

  let quoteUpdateData: Prisma.QuoteUpdateInput = {
    ...(data.customerId !== undefined && { customerId: data.customerId }),
    ...(data.subject !== undefined && { subject: data.subject }),
    ...(data.issueDate !== undefined && { issueDate: new Date(data.issueDate as string) }),
    ...(data.expiryDate !== undefined && { expiryDate: new Date(data.expiryDate as string) }),
    ...(data.currency !== undefined && { currency: data.currency }),
    ...(data.notes !== undefined && { notes: data.notes }),
    ...(data.terms !== undefined && { terms: data.terms }),
    ...(data.reference !== undefined && { reference: data.reference }),
  };

  if (data.items && data.items.length > 0) {
    let subtotal = 0;
    let totalTaxAmount = 0;
    let totalDiscountAmount = 0;

    const itemsData = data.items.map((item, index) => {
      const discount = item.discount ?? 0;
      const { baseAmount, taxAmount, total } = calcItemTotals({ ...item, discount });
      const discountAmountForItem = round2(item.quantity * item.unitPrice * (discount / 100));
      subtotal += baseAmount;
      totalTaxAmount += taxAmount;
      totalDiscountAmount += discountAmountForItem;
      return {
        description: item.description,
        quantity: item.quantity,
        unitPrice: item.unitPrice,
        taxRate: item.taxRate,
        taxAmount,
        discount,
        total,
        order: item.order ?? index,
      };
    });

    subtotal = round2(subtotal);
    totalTaxAmount = round2(totalTaxAmount);
    totalDiscountAmount = round2(totalDiscountAmount);
    const quoteTotal = round2(subtotal + totalTaxAmount);

    quoteUpdateData = {
      ...quoteUpdateData,
      subtotal,
      taxAmount: totalTaxAmount,
      discountAmount: totalDiscountAmount,
      total: quoteTotal,
    };

    const updated = await prisma.$transaction(async (tx) => {
      await tx.quoteItem.deleteMany({ where: { quoteId: id } });
      return tx.quote.update({
        where: { id },
        data: {
          ...quoteUpdateData,
          items: { create: itemsData },
        },
        include: {
          customer: { select: { id: true, name: true, email: true } },
          items: { orderBy: { order: "asc" } },
        },
      });
    });

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

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

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

// ─── DELETE /api/quotes/[id] ───────────────────────────────────

export async function DELETE(
  _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 quote = await prisma.quote.findFirst({
    where: { id, organizationId },
  });

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

  if (quote.status === "CONVERTED") {
    return NextResponse.json(
      { success: false, error: "Un devis converti en facture ne peut pas être supprimé" },
      { status: 409 }
    );
  }

  await prisma.quote.delete({ where: { id } });

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