import { NextRequest } from "next/server";
import { PaymentType } from "@prisma/client";
import { z } from "zod";
import { prisma } from "@/server/db";
import { env } from "@/server/env";
import { fail, ok, parseJson } from "@/server/http";
import { createPaymentProvider } from "@/server/providers/payment/factory";
import { requireUser } from "@/server/security/auth";
import { ensureWallet } from "@/server/wallet/ledger";

const schema = z.object({
  amount: z.coerce.number().positive().max(100000),
  currency: z.string().min(3).max(8),
  method: z.string().min(1).max(40).optional()
});

export async function POST(request: NextRequest) {
  try {
    const { user } = await requireUser(request);
    const input = await parseJson(request, schema);
    const wallet = await ensureWallet(user.id, input.currency);
    const provider = createPaymentProvider();
    const idempotencyKey = crypto.randomUUID();
    const intent = await provider.createDepositIntent({
      userId: user.id,
      amount: String(input.amount),
      currency: input.currency,
      idempotencyKey,
      returnUrl: `${env().APP_URL}/wallet`
    });

    const transaction = await prisma.paymentTransaction.create({
      data: {
        userId: user.id,
        walletId: wallet.id,
        type: PaymentType.DEPOSIT,
        provider: intent.provider,
        providerRef: intent.providerRef,
        status: "PENDING",
        amount: input.amount,
        currency: input.currency,
        idempotencyKey,
        method: input.method
      }
    });

    return ok({ transactionId: transaction.id, redirectUrl: intent.redirectUrl, providerRef: intent.providerRef });
  } catch (error) {
    return fail(error);
  }
}
