import { NextRequest } from "next/server";
import { prisma } from "@/server/db";
import { fail, ok, parseJson } from "@/server/http";
import { requireUser } from "@/server/security/auth";
import { createCryptoWithdrawal, createCryptoWithdrawalSchema } from "@/server/crypto/payments";

export const dynamic = "force-dynamic";

export async function GET(request: NextRequest) {
  try {
    const { user } = await requireUser(request);
    const withdrawals = await prisma.cryptoWithdrawal.findMany({
      where: { userId: user.id },
      orderBy: { createdAt: "desc" },
      take: 20
    });

    return ok({ withdrawals: withdrawals.map(serializeWithdrawal) });
  } catch (error) {
    return fail(error);
  }
}

export async function POST(request: NextRequest) {
  try {
    const { user } = await requireUser(request);
    const input = await parseJson(request, createCryptoWithdrawalSchema);
    const withdrawal = await createCryptoWithdrawal({
      userId: user.id,
      asset: input.asset,
      amountEur: input.amountEur,
      destinationAddress: input.destinationAddress
    });

    return ok({ withdrawal: serializeWithdrawal(withdrawal) });
  } catch (error) {
    return fail(error);
  }
}

function serializeWithdrawal(withdrawal: Awaited<ReturnType<typeof prisma.cryptoWithdrawal.findMany>>[number]) {
  return {
    id: withdrawal.id,
    asset: withdrawal.asset,
    network: withdrawal.network,
    destinationAddress: withdrawal.destinationAddress,
    eurAmount: withdrawal.eurAmount.toString(),
    feeEur: withdrawal.feeEur.toString(),
    totalDebitEur: withdrawal.totalDebitEur.toString(),
    cryptoAmount: withdrawal.cryptoAmount.toString(),
    eurRate: withdrawal.eurRate.toString(),
    rateSource: withdrawal.rateSource,
    status: withdrawal.status,
    txHash: withdrawal.txHash,
    reviewReason: withdrawal.reviewReason,
    createdAt: withdrawal.createdAt,
    reviewedAt: withdrawal.reviewedAt
  };
}
