import prismadb from "@/lib/prismadb";
import { auth } from '@clerk/nextjs/server'
import { NextResponse } from "next/server";

// POST a new transaction
export async function POST(
    req: Request,
    { params }: { params: { storeId: string } }
) {
    try {
        const { userId } = auth();
        const body = await req.json();

        const {
            status, // Ensure this is from the transaction_status enum
            total, // Change from totalAmount to total
            transaction_method, // Change from paymentMethod to transaction_method
            transactionItems,
            customer_name, // Add customer_name
            customer_email, // Add customer_email
        } = body;

        if (!userId) {
            return new NextResponse("Unauthenticated", { status: 401 });
        }

        if (!status) {
            return new NextResponse("Status is required", { status: 400 });
        }

        if (total == null) { // Check for total
            return new NextResponse("Total amount is required", { status: 400 });
        }

        if (!transaction_method) { // Check for transaction method
            return new NextResponse("Payment method is required", { status: 400 });
        }

        if (!customer_name) { // Check for customer name
            return new NextResponse("Customer name is required", { status: 400 });
        }

        if (!customer_email) { // Check for customer email
            return new NextResponse("Customer email is required", { status: 400 });
        }

        if (!transactionItems || transactionItems.length === 0) {
            return new NextResponse("Transaction items are required", { status: 400 });
        }

        if (!params.storeId) {
            return new NextResponse("Store ID is required", { status: 400 });
        }

        const storeByUserId = await prismadb.store.findFirst({
            where: {
                id: params.storeId,
                userId,
            },
        });

        if (!storeByUserId) {
            return new NextResponse("Unauthorized", { status: 403 });
        }

        const transaction = await prismadb.transaction.create({
            data: {
                status, // Ensure status matches the enum
                total, // Use the updated field
                transaction_method, // Use the updated field
                userId, // You might want to store the userId in the transaction
                customer_name, // Add customer name
                customer_email, // Add customer email
                addressId: null, // Assign this if you have a relevant value
                transactionitem: {
                    create: transactionItems.map((item: any) => ({
                        itemId: item.id, // This assumes itemId is from transactionitem relation
                        quantity: item.quantity,
                        price: item.price,
                    })),
                },
                createdAt: new Date(), // Auto-generated, but included for clarity
                updatedAt: new Date(),
            },
        });

        return NextResponse.json(transaction);
    } catch (error) {
        console.log('[TRANSACTION_POST]', error);
        return new NextResponse("Internal error", { status: 500 });
    }
}

// GET transactions for a store
export async function GET(
    req: Request,
    { params }: { params: { storeId: string } }
) {
    try {
        if (!params.storeId) {
            return new NextResponse("Store ID is required", { status: 400 });
        }

        const transactions = await prismadb.transaction.findMany({
            include: {
                transactionitem: true, // Include transaction items
            },
            orderBy: {
                createdAt: 'desc',
            },
        });

        console.log('transactions', transactions);

        return NextResponse.json(transactions);
    } catch (error) {
        console.log('[TRANSACTION_GET]', error);
        return new NextResponse("Internal error", { status: 500 });
    }
}
