import { NextResponse } from 'next/server';
import { z } from 'zod';

import { withAuth } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { AppError, errorResponse } from '@/lib/errors';
import { convert } from '@/lib/services/currency';

const convertSchema = z.object({
  amount: z.coerce.number().positive(),
  from: z.string().length(3),
  to: z.string().length(3),
});

export const POST = withAuth(async (req, _ctx) => {
  try {
    const { amount, from, to } = await parseBody(req, convertSchema);

    const result = await convert(amount, from, to);

    if (!result) {
      // 422 (not 400): the input is well-formed, but no rate is
      // available for the requested pair. Routed through errorResponse
      // so the body carries code + requestId like every other error.
      throw new AppError(
        422,
        `Exchange rate not available for ${from} → ${to}`,
        'CURRENCY_RATE_UNAVAILABLE',
      );
    }

    return NextResponse.json({ data: result });
  } catch (error) {
    return errorResponse(error);
  }
});
