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

const updateSchema = z.object({
  name: z.string().min(1).optional(),
  email: z.string().email().optional().or(z.literal("")),
  phone: z.string().optional(),
  address: z.string().optional(),
  city: z.string().optional(),
  postalCode: z.string().optional(),
  country: z.string().optional(),
  vatNumber: z.string().optional(),
  siret: z.string().optional(),
  notes: z.string().optional(),
  isActive: z.boolean().optional(),
});

async function getOrgId(userId: string) {
}

export async function GET(_req: Request, { 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 { id } = await params;

  const customer = await prisma.customer.findFirst({
    where: { id, organizationId: orgId ?? "" },
    include: {
      invoices: {
        orderBy: { createdAt: "desc" },
        take: 10,
        select: { id: true, number: true, total: true, status: true, issueDate: true },
      },
    },
  });

  if (!customer) return NextResponse.json({ success: false, error: "Client introuvable" }, { status: 404 });
  return NextResponse.json({ success: true, data: customer });
}

export async function PATCH(req: Request, { 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 { id } = await params;
  const body = await req.json();
  const parsed = updateSchema.safeParse(body);
  if (!parsed.success) return NextResponse.json({ success: false, error: "Données invalides" }, { status: 400 });

  const existing = await prisma.customer.findFirst({ where: { id, organizationId: orgId ?? "" } });
  if (!existing) return NextResponse.json({ success: false, error: "Client introuvable" }, { status: 404 });

  const updated = await prisma.customer.update({ where: { id }, data: parsed.data });
  return NextResponse.json({ success: true, data: updated });
}

export async function DELETE(_req: Request, { 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 { id } = await params;

  const existing = await prisma.customer.findFirst({ where: { id, organizationId: orgId ?? "" } });
  if (!existing) return NextResponse.json({ success: false, error: "Client introuvable" }, { status: 404 });

  // Soft delete
  await prisma.customer.update({ where: { id }, data: { isActive: false } });
  return NextResponse.json({ success: true });
}
