import type { APIRoute } from 'astro';
import { generateShortLink } from '../../utils/shortlink';

export const POST: APIRoute = async ({ request }) => {
  try {
    const { url } = await request.json();

    if (!url) {
      return new Response(JSON.stringify({ error: 'URL is required' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    const shortLink = await generateShortLink(url);

    return new Response(JSON.stringify({ shortLink }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    console.error('Error generating short link:', error);
    return new Response(JSON.stringify({ error: 'Failed to generate short link' }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};
