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

export async function GET(req: NextRequest) {
  const jwtPayload = await requireAuth(req);
  if (!jwtPayload) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const user = await prisma.user.findUnique({
    where: { id: jwtPayload.userId },
    include: {
      cashouts: {
        orderBy: { createdAt: "desc" },
        take: 50,
      },
    },
  });

  if (!user) {
    return NextResponse.json({ error: "User not found" }, { status: 404 });
  }

  return NextResponse.json({
    balance: user.flhBalance,
    cashoutHistory: user.cashouts.map((c) => ({
      id: c.id,
      amountFlh: c.amountFlh,
      fiatAmount: c.fiatAmount,
      status: c.status,
      createdAt: c.createdAt,
    })),
  });
}

export async function POST(req: NextRequest) {
  const jwtPayload = await requireAuth(req);
  if (!jwtPayload) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const body = await req.json();
    const { amountFlh } = body;

    if (!amountFlh || typeof amountFlh !== "number" || amountFlh < 1000) {
      return NextResponse.json(
        { error: "Minimum cashout is 1,000 FLH" },
        { status: 400 }
      );
    }

    const user = await prisma.user.findUnique({
      where: { id: jwtPayload.userId },
    });

    if (!user) {
      return NextResponse.json({ error: "User not found" }, { status: 404 });
    }

    if (user.flhBalance < amountFlh) {
      return NextResponse.json(
        { error: "Insufficient FLH balance" },
        { status: 400 }
      );
    }

    // Fiat conversion: 1000 FLH = $1.00
    const fiatAmount = Math.round((amountFlh / 1000) * 100) / 100;

    const cashout = await prisma.cashoutRequest.create({
      data: {
        userId: user.id,
        amountFlh,
        fiatAmount,
        status: "pending",
      },
    });

    // Deduct balance immediately
    await prisma.user.update({
      where: { id: user.id },
      data: { flhBalance: { decrement: amountFlh } },
    });

    return NextResponse.json({
      success: true,
      cashout: {
        id: cashout.id,
        amountFlh: cashout.amountFlh,
        fiatAmount: cashout.fiatAmount,
        status: cashout.status,
        createdAt: cashout.createdAt,
      },
    });
  } catch (error) {
    console.error("Cashout error:", error);
    return NextResponse.json(
      { error: "Cashout request failed" },
      { status: 500 }
    );
  }
}
