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

// ─── Helper : récupérer l'organisation de l'utilisateur ──────
async function getOrganization(userId: string) {
  const membership = await prisma.organizationMember.findFirst({
    where: { userId, joinedAt: { not: null } },
    include: { organization: true },
    orderBy: { createdAt: "asc" },
  });
  return membership?.organization ?? null;
}

const approveSchema = z.object({
  action: z.enum(["approve", "reject"]),
});

// ─── POST /api/expenses/[id]/approve ─────────────────────────
export async function POST(
  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 { id } = await params;

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

  const body = await request.json().catch(() => null);
  if (!body) {
    return NextResponse.json({ success: false, error: "Corps de requête invalide" }, { status: 400 });
  }

  const parsed = approveSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json(
      { success: false, error: "Action invalide. Utilisez \"approve\" ou \"reject\"." },
      { status: 422 }
    );
  }

  const newStatus = parsed.data.action === "approve" ? "APPROVED" : "REJECTED";

  const updated = await prisma.expense.update({
    where: { id },
    data: { status: newStatus },
    include: {
      category: { select: { id: true, name: true, color: true } },
      supplier: { select: { id: true, name: true } },
    },
  });

  const label = newStatus === "APPROVED" ? "approuvée" : "rejetée";

  return NextResponse.json({
    success: true,
    data: updated,
    message: `Dépense ${label} avec succès`,
  });
}
