import { NextRequest, NextResponse } from 'next/server';
import { isPostgresProviderEnabled } from '@/lib/config';
import { pgCreateCurrency, pgGetCurrencies } from '@/lib/postgres/data-access';

export async function GET() {
  try {
    const usePostgres = isPostgresProviderEnabled();
    const currencies = usePostgres
      ? (await pgGetCurrencies({ page: 1, pageSize: 5000 })).items
      : (await import('@/lib/data')).getCurrencies();
    return NextResponse.json(currencies);
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to fetch currencies' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const usePostgres = isPostgresProviderEnabled();
    const newCurrency = usePostgres
      ? await pgCreateCurrency(body)
      : (await import('@/lib/data')).addCurrency(body);
    return NextResponse.json(newCurrency, { status: 201 });
  } catch (error) {
    const message = String((error as any)?.message || '');
    const code = String((error as any)?.code || '');

    if (message === 'CURRENCY_CODE_REQUIRED') {
      return NextResponse.json({ error: 'Currency code is required' }, { status: 400 });
    }

    if (message === 'CURRENCY_CODE_EXISTS' || code === '23505') {
      return NextResponse.json({ error: 'Currency code already exists' }, { status: 409 });
    }

    if (message === 'CURRENCY_REFERENCE_EXISTS') {
      return NextResponse.json({ error: 'Currency reference already exists' }, { status: 409 });
    }

    return NextResponse.json(
      { error: 'Failed to add currency' },
      { status: 500 }
    );
  }
}
