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

import { withAuth } from '@/lib/api/helpers';
import { 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 body = await req.json();
    const { amount, from, to } = convertSchema.parse(body);

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

    if (!result) {
      return NextResponse.json(
        { error: `Exchange rate not available for ${from} → ${to}` },
        { status: 422 },
      );
    }

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