import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/infrastructure/db/prisma";
import { withAuth, ROLES } from "@/middleware/auth";

export async function POST(request: NextRequest) {
  const result = await withAuth(request, [ROLES.ASSISTANT, ROLES.THERAPIST]);

  if (result instanceof NextResponse) {
    return result;
  }

  const { user } = result;

  try {
    const body = await request.json();
    const { paymentId, action, reason } = body;

    if (!paymentId || !action || !["approve", "reject"].includes(action)) {
      return NextResponse.json({ error: "Invalid request" }, { status: 400 });
    }

    const updateData: any = {
      status: action === "approve" ? "APPROVED" : "REJECTED",
      approvedBy: user.id,
    };

    if (action === "approve") {
      updateData.approvedAt = new Date();
    } else {
      updateData.rejectedReason = reason;
      updateData.rejectedAt = new Date();
    }

    await prisma.payment.update({
      where: { id: paymentId },
      data: updateData,
    });

    return NextResponse.json({
      success: true,
      message: `Payment ${action === "approve" ? "approved" : "rejected"} successfully`,
    });
  } catch (error) {
    console.error("Payment validation error:", error);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
