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 supplier = await prisma.supplier.findFirst({
    where: { id, organizationId: orgId ?? "" },
    include: {
      expenses: {
        orderBy: { date: "desc" },
        take: 10,
        select: { id: true, description: true, amount: true, status: true, date: true },
      },
      _count: { select: { expenses: true } },
    },
  });

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

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.supplier.findFirst({ where: { id, organizationId: orgId ?? "" } });
  if (!existing) return NextResponse.json({ success: false, error: "Fournisseur introuvable" }, { status: 404 });

  const updated = await prisma.supplier.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.supplier.findFirst({ where: { id, organizationId: orgId ?? "" } });
  if (!existing) return NextResponse.json({ success: false, error: "Fournisseur introuvable" }, { status: 404 });

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