2024-08-12 17:27:47 -05:00
|
|
|
import { addResourcePurchaseToUser } from "@/db/models/userModels";
|
2024-10-02 17:27:38 -05:00
|
|
|
import { getServerSession } from "next-auth/next"
|
|
|
|
import { authOptions } from "@/pages/api/auth/[...nextauth]"
|
2024-08-11 19:10:08 -05:00
|
|
|
|
|
|
|
export default async function handler(req, res) {
|
2024-10-02 17:27:38 -05:00
|
|
|
const session = await getServerSession(req, res, authOptions)
|
|
|
|
|
|
|
|
if (!session) {
|
|
|
|
return res.status(401).json({ error: 'Unauthorized' });
|
|
|
|
}
|
|
|
|
|
2024-08-11 19:10:08 -05:00
|
|
|
if (req.method === 'POST') {
|
|
|
|
try {
|
|
|
|
const { userId, resourceId, amountPaid } = req.body;
|
|
|
|
|
2024-10-12 13:43:35 -05:00
|
|
|
if (!userId || !resourceId || !amountPaid) {
|
|
|
|
return res.status(400).json({ error: 'Missing required fields' });
|
|
|
|
}
|
|
|
|
|
2024-08-12 17:27:47 -05:00
|
|
|
const updatedUser = await addResourcePurchaseToUser(userId, {
|
2024-08-11 19:10:08 -05:00
|
|
|
resourceId,
|
2024-10-12 13:43:35 -05:00
|
|
|
amountPaid: parseInt(amountPaid, 10)
|
2024-08-11 19:10:08 -05:00
|
|
|
});
|
|
|
|
|
|
|
|
res.status(200).json(updatedUser);
|
|
|
|
} catch (error) {
|
2024-10-12 13:43:35 -05:00
|
|
|
console.error('Error in resource purchase:', error);
|
|
|
|
res.status(500).json({ error: 'An error occurred while processing the purchase' });
|
2024-08-11 19:10:08 -05:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
res.setHeader('Allow', ['POST']);
|
|
|
|
res.status(405).end(`Method ${req.method} Not Allowed`);
|
|
|
|
}
|
2024-10-12 13:43:35 -05:00
|
|
|
}
|