import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db/client';
import { generateMetaXmlFeed } from '@/lib/meta/feed';

export const dynamic = 'force-dynamic';

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

    let shop = null;
    if (shopDomain) {
      shop = await db.getShopByDomain(shopDomain);
    }
    if (!shop && process.env.NODE_ENV !== 'production') {
      shop = await db.getDefaultShop();
    }
    if (!shop) {
      return new NextResponse('<error>Valid "shop" query parameter is required</error>', {
        status: 400,
        headers: { 'Content-Type': 'application/xml' },
      });
    }

    const products = await db.getProductsByShopId(shop.id);
    const xml = generateMetaXmlFeed(products, shop.shopify_domain);

    return new NextResponse(xml, {
      status: 200,
      headers: {
        'Content-Type': 'application/xml; charset=utf-8',
        'Cache-Control': 'public, max-age=3600, s-maxage=3600',
      },
    });
  } catch (err) {
    return new NextResponse(`<error>${err instanceof Error ? err.message : 'Internal Server Error'}</error>`, {
      status: 500,
      headers: { 'Content-Type': 'application/xml' },
    });
  }
}
