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(),
  rate:      z.coerce.number().min(0).max(100).optional(),
  isDefault: z.boolean().optional(),
  isActive:  z.boolean().optional(),
});

async function getOrgId(userId: string) {
}

export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    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.taxRate.findFirst({ where: { id, organizationId: orgId } });
    if (!existing) return NextResponse.json({ success: false, error: "Taux introuvable" }, { status: 404 });

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

    // Si on met ce taux en défaut, retirer le défaut des autres
    if (parsed.data.isDefault) {
      await prisma.taxRate.updateMany({
        where: { organizationId: orgId, isDefault: true, id: { not: id } },
        data: { isDefault: false },
      });
    }

    const updated = await prisma.taxRate.update({ where: { id }, data: parsed.data });
    return NextResponse.json({ success: true, data: updated });
  } catch (err: any) {
    if (err?.code === "P2002") {
      return NextResponse.json({ success: false, error: "Un taux avec ce nom existe déjà" }, { status: 409 });
    }
    return NextResponse.json({ success: false, error: "Erreur serveur", detail: err?.message }, { status: 500 });
  }
}

export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    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.taxRate.findFirst({ where: { id, organizationId: orgId } });
    if (!existing) return NextResponse.json({ success: false, error: "Taux introuvable" }, { status: 404 });

    await prisma.taxRate.delete({ where: { id } });
    return NextResponse.json({ success: true });
  } catch (err: any) {
    return NextResponse.json({ success: false, error: "Erreur serveur", detail: err?.message }, { status: 500 });
  }
}
