// app/api/transactions/refund/route.ts
import { NextRequest, NextResponse } from "next/server";
import Transaction from "@/models/transactions";
import { User } from "@/models/user";
import dbConnect from "@/lib/connectdb";
import { authOptions } from "@/auth";
import { getServerSession } from "next-auth";

export async function POST(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    if (!session || session.user.role !== "admin") {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    await dbConnect();

    const { transactionId, referenceId, userId, amount } = await req.json();

    if (!transactionId || !referenceId || !userId || !amount) {
      return NextResponse.json(
        { success: false, error: "Missing required fields" },
        { status: 400 }
      );
    }

    // Validate amount is a number
    const refundAmount = Number(amount);
    if (isNaN(refundAmount)) {
      return NextResponse.json(
        { success: false, error: "Invalid amount" },
        { status: 400 }
      );
    }

    // Check if transaction exists and is failed
    const transaction = await Transaction.findById(transactionId);
    if (!transaction) {
      return NextResponse.json(
        { success: false, error: "Transaction not found" },
        { status: 404 }
      );
    }
    if (transaction.refund) {
      return NextResponse.json(
        { success: false, error: "Transaction already refunded" },
        { status: 400 }
      );
    }

    // Find user and update balance
    const user = await User.findById(userId);
    if (!user) {
      return NextResponse.json(
        {
          success: false,
          error: "If the user exists, they will be handled accordingly.",
        },
        { status: 404 }
      );
    }

    // Ensure walletBalance is a number
    const currentBalance = Number(user.accountBalance) || 0;

    // Update user balance
    const newBalance = currentBalance + refundAmount;
    user.accountBalance = newBalance;
    await user.save();

    // Mark original transaction as refunded
    transaction.refund = true;
    transaction.status = "Failed";
    await transaction.save();

    // Create a refund transaction record
    const refundTransaction = new Transaction({
      type: "RefundTransaction",
      amount: refundAmount,
      balanceBefore: currentBalance, // Use the balance before adding the refund
      balanceAfter: newBalance, // Use the new balance after adding the refund
      status: "Successful",
      userId: userId,
      referenceId: `REFUND-${referenceId}`,
      refund: false, // This is the refund transaction itself
    });
    await refundTransaction.save();

    return NextResponse.json({
      success: true,
      message: "Refund processed successfully",
      newBalance: newBalance,
    });
  } catch (error) {
    console.error("Error processing refund:", error);
    return NextResponse.json(
      { success: false, error: "Failed to process refund" },
      { status: 500 }
    );
  }
}
