Files
fintrack/app/api/banking/accounts/route.ts

110 lines
3.0 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { accountService } from "@/services/account.service";
import { bankingService } from "@/services/banking.service";
import { requireAuth } from "@/lib/auth-utils";
import type { Account } from "@/lib/types";
export async function GET(request: NextRequest) {
const authError = await requireAuth();
if (authError) return authError;
try {
const { searchParams } = new URL(request.url);
const withStats = searchParams.get("withStats") === "true";
if (withStats) {
const accountsWithStats = await bankingService.getAccountsWithStats();
return NextResponse.json(accountsWithStats, {
headers: {
"Cache-Control": "public, s-maxage=60, stale-while-revalidate=120",
},
});
}
return NextResponse.json(
{ error: "Invalid request" },
{ status: 400 },
);
} catch (error) {
console.error("Error fetching accounts:", error);
return NextResponse.json(
{ error: "Failed to fetch accounts" },
{ status: 500 },
);
}
}
export async function POST(request: Request) {
const authError = await requireAuth();
if (authError) return authError;
try {
const data: Omit<Account, "id"> = await request.json();
const created = await accountService.create(data);
return NextResponse.json(created);
} catch (error) {
console.error("Error creating account:", error);
return NextResponse.json(
{ error: "Failed to create account" },
{ status: 500 },
);
}
}
export async function PUT(request: Request) {
const authError = await requireAuth();
if (authError) return authError;
try {
const account: Account = await request.json();
const updated = await accountService.update(account.id, account);
return NextResponse.json(updated);
} catch (error) {
console.error("Error updating account:", error);
return NextResponse.json(
{ error: "Failed to update account" },
{ status: 500 },
);
}
}
export async function DELETE(request: Request) {
const authError = await requireAuth();
if (authError) return authError;
try {
const { searchParams } = new URL(request.url);
const id = searchParams.get("id");
const ids = searchParams.get("ids");
if (ids) {
// Multiple deletion
const accountIds = ids.split(",").filter(Boolean);
if (accountIds.length === 0) {
return NextResponse.json(
{ error: "At least one account ID is required" },
{ status: 400 },
);
}
await accountService.deleteMany(accountIds);
return NextResponse.json({ success: true, count: accountIds.length });
}
if (!id) {
return NextResponse.json(
{ error: "Account ID is required" },
{ status: 400 },
);
}
await accountService.delete(id);
return NextResponse.json({ success: true });
} catch (error) {
console.error("Error deleting account:", error);
return NextResponse.json(
{ error: "Failed to delete account" },
{ status: 500 },
);
}
}