import { NextRequest, 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(),
  description: z.string().optional(),
  reference:   z.string().optional(),
  unit:        z.string().optional(),
  category:    z.string().optional(),
  unitPrice:   z.coerce.number().min(0).optional(),
  taxRate:     z.coerce.number().min(0).max(100).optional(),
  isActive:    z.boolean().optional(),
});

async function getOrgId(userId: string) {
}

// GET /api/products/[id]
export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const ctx = await getSessionContext();
    if (!ctx) return NextResponse.json({ success: false, error: "Non authentifié ou organisation introuvable" }, { status: 401 });
    const { userId, orgId } = ctx;

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

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

// PATCH /api/products/[id]
export async function PATCH(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const ctx = await getSessionContext();
    if (!ctx) return NextResponse.json({ success: false, error: "Non authentifié ou organisation introuvable" }, { status: 401 });
    const { userId, orgId } = ctx;

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

  const body = await req.json().catch(() => ({}));
  const parsed = updateSchema.safeParse(body);
  if (!parsed.success) return NextResponse.json({ success: false, error: "Données invalides" }, { status: 400 });

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

// DELETE /api/products/[id]
export async function DELETE(
  _req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const ctx = await getSessionContext();
    if (!ctx) return NextResponse.json({ success: false, error: "Non authentifié ou organisation introuvable" }, { status: 401 });
    const { userId, orgId } = ctx;

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

  await prisma.product.delete({ where: { id } });
  return NextResponse.json({ success: true });
}
