import { db } from "@/config/firebase";
import { decodeToken } from "@/helpers/decodeToken";
import { NextResponse } from "next/server";
import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server";
export const GET = async (req) => {
try {
const {refreshTokens} = getKindeServerSession();
const tokens = await refreshTokens(req);
console.log(tokens)
const { sub: user, error } = await decodeToken(req);
if (error) {
return NextResponse.json({ error: "Not a valid token" }, { status: 401 });
}
const { searchParams } = new URL(req.url);
const pageSize = parseInt(searchParams.get("pageSize") || "5", 10);
let query = db
.collection("receipts")
.where("user", "==", user)
.limit(pageSize);
const receipts = await query.get();
if (receipts.empty) {
return NextResponse.json({ data: [], message: "No more data." });
}
const data = receipts.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));
return NextResponse.json({
data,
message: "Data fetched successfully.",
});
} catch (error) {
console.error("Error fetching receipts:", error);
return NextResponse.json(
{ error: "Failed to fetch receipts." },
{ status: 500 }
);
}
};