import { NextRequest, NextResponse } from "next/server";

import { pgDeleteCurrencyByCode, pgGetCurrencyByCode, pgUpdateCurrencyByCode } from "@/lib/postgres/data-access";

export async function PUT(request: NextRequest, { params }: { params: Promise<{ code: string }> }) {
  try {
    const resolvedParams = await params;
    const code = decodeURIComponent(resolvedParams.code);
    const body = await request.json();
    const updated = await pgUpdateCurrencyByCode(code, body);
    if (!updated) {
      return NextResponse.json({ error: "Currency not found" }, { status: 404 });
    }
    return NextResponse.json(updated);
  } catch (error) {
    return NextResponse.json({ error: "Failed to update currency" }, { status: 500 });
  }
}

export async function DELETE(request: NextRequest, { params }: { params: Promise<{ code: string }> }) {
  try {
    const resolvedParams = await params;
    const code = decodeURIComponent(resolvedParams.code);
    const currency = await pgGetCurrencyByCode(code);
    if (!currency) {
      return NextResponse.json({ error: "Currency not found" }, { status: 404 });
    }
    const deleted = await pgDeleteCurrencyByCode(code);
    if (!deleted) {
      return NextResponse.json({ error: "Cannot delete default currency" }, { status: 400 });
    }
    return NextResponse.json({ success: true });
  } catch (error) {
    return NextResponse.json({ error: "Failed to delete currency" }, { status: 500 });
  }
}
