import { NextRequest, NextResponse } from 'next/server';
import { typedQuery } from '@/backend/utils/typedQuery';

type TypeRow = {
  description: string;
};

export async function GET(req: NextRequest) {
  const { searchParams } = new URL(req.url);
  const code = searchParams.get('code');

  if (!code) {
    return NextResponse.json({ error: 'Missing code parameter' }, { status: 400 });
  }

  try {
    const [rows] = await typedQuery<TypeRow>(
      'SELECT cardtypedesc description FROM cardtypes WHERE useascategory = 1 AND idcardtype = ? LIMIT 1',
      [code]
    );

    if (rows.length === 0) {
      return NextResponse.json({ error: 'Type not found' }, { status: 404 });
    }

    return NextResponse.json({ description: rows[0].description });
  } catch (error) {
    console.error('DB error:', error);
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
  }
}
