import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { verifyAdminPermission } from '@/lib/auth';

// GET - List all payment transactions (admin)
export async function GET(request: NextRequest) {
  try {
    const authResult = await verifyAdminPermission(request, 'canManageOrders');
    if ('error' in authResult) return authResult.error;

    const { searchParams } = new URL(request.url);
    const status = searchParams.get('status');
    const gatewayId = searchParams.get('gatewayId');
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '50');
    const skip = (page - 1) * limit;

    const where: Record<string, unknown> = {};
    if (status && status !== 'all') where.status = status;
    if (gatewayId) where.gatewayId = gatewayId;

    const [transactions, total] = await Promise.all([
      db.paymentTransaction.findMany({
        where,
        orderBy: { createdAt: 'desc' },
        skip,
        take: limit,
        include: {
          user: {
            select: { id: true, name: true, email: true, avatar: true },
          },
          gateway: {
            select: { id: true, name: true, icon: true, type: true, slug: true },
          },
        },
      }),
      db.paymentTransaction.count({ where }),
    ]);

    // Compute summary stats (global, not filtered by status to always show full context)
    const stats = await db.paymentTransaction.aggregate({
      _sum: { amount: true },
      _count: true,
    });

    const completedStats = await db.paymentTransaction.aggregate({
      where: { status: 'completed' },
      _sum: { amount: true },
      _count: true,
    });

    const pendingStats = await db.paymentTransaction.aggregate({
      where: { status: 'pending' },
      _sum: { amount: true },
      _count: true,
    });

    // If filtering by gatewayId, also compute filtered stats for context
    let filteredStats = null;
    if (gatewayId) {
      const gwStats = await db.paymentTransaction.aggregate({
        where: { gatewayId },
        _sum: { amount: true },
        _count: true,
      });
      const gwCompleted = await db.paymentTransaction.aggregate({
        where: { gatewayId, status: 'completed' },
        _sum: { amount: true },
        _count: true,
      });
      const gwPending = await db.paymentTransaction.aggregate({
        where: { gatewayId, status: 'pending' },
        _sum: { amount: true },
        _count: true,
      });
      filteredStats = {
        totalAmount: gwStats._sum.amount || 0,
        totalTransactions: gwStats._count,
        completedAmount: gwCompleted._sum.amount || 0,
        completedCount: gwCompleted._count,
        pendingAmount: gwPending._sum.amount || 0,
        pendingCount: gwPending._count,
      };
    }

    return NextResponse.json({
      success: true,
      transactions,
      total,
      page,
      limit,
      stats: {
        totalAmount: stats._sum.amount || 0,
        totalTransactions: stats._count,
        completedAmount: completedStats._sum.amount || 0,
        completedCount: completedStats._count,
        pendingAmount: pendingStats._sum.amount || 0,
        pendingCount: pendingStats._count,
      },
      ...(filteredStats ? { filteredStats } : {}),
    });
  } catch (error) {
    console.error('Payment transactions fetch error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to fetch payment transactions' },
      { status: 500 }
    );
  }
}

// PATCH - Update a payment transaction status (admin verify/reject)
export async function PATCH(request: NextRequest) {
  try {
    const authResult = await verifyAdminPermission(request, 'canManageOrders');
    if ('error' in authResult) return authResult.error;

    const body = await request.json();
    const { transactionId, status, gatewayTransactionId, gatewayResponse } = body;

    if (!transactionId || !status) {
      return NextResponse.json(
        { success: false, error: 'transactionId and status are required' },
        { status: 400 }
      );
    }

    const validStatuses = ['pending', 'processing', 'completed', 'failed', 'refunded'];
    if (!validStatuses.includes(status)) {
      return NextResponse.json(
        { success: false, error: `Invalid status. Must be one of: ${validStatuses.join(', ')}` },
        { status: 400 }
      );
    }

    const existing = await db.paymentTransaction.findUnique({ where: { id: transactionId } });
    if (!existing) {
      return NextResponse.json(
        { success: false, error: 'Transaction not found' },
        { status: 404 }
      );
    }

    const updateData: Record<string, unknown> = { status };
    if (gatewayTransactionId) updateData.transactionId = gatewayTransactionId;
    if (gatewayResponse) {
      updateData.gatewayResponse =
        typeof gatewayResponse === 'object' ? JSON.stringify(gatewayResponse) : gatewayResponse;
    }

    const transaction = await db.paymentTransaction.update({
      where: { id: transactionId },
      data: updateData,
    });

    return NextResponse.json({ success: true, transaction });
  } catch (error) {
    console.error('Payment transaction update error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to update payment transaction' },
      { status: 500 }
    );
  }
}
