import { NextResponse } from 'next/server';
import crypto from 'node:crypto';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { getStorefrontProfile, getStorefrontMenu } from '@server/services/storefront.service';

export const GET = withErrorHandler(async (req: Request, ctx: RouteContext) => {
  const { restaurantSlug, branchSlug } = await ctx.params;
  const profile = await getStorefrontProfile(restaurantSlug, branchSlug);
  if (!profile) return NextResponse.json({ error: 'Storefront not found' }, { status: 404 });
  if (!profile.feature_enabled) return NextResponse.json({ error: 'Storefront feature locked' }, { status: 402 });
  if (!profile.branch.storefront_enabled) return NextResponse.json({ error: 'Storefront disabled' }, { status: 503 });

  const categories = await getStorefrontMenu(profile.restaurant.id as string, profile.branch.id as string);
  const body = JSON.stringify({ categories });
  const etag = `W/"${crypto.createHash('sha1').update(body).digest('base64')}"`;
  if (req.headers.get('if-none-match') === etag) {
    return new NextResponse(null, {
      status: 304,
      headers: { ETag: etag, 'Cache-Control': 'public, max-age=0, must-revalidate' },
    });
  }
  return new NextResponse(body, {
    status: 200,
    headers: {
      'Content-Type': 'application/json; charset=utf-8',
      'Cache-Control': 'public, max-age=0, must-revalidate',
      ETag: etag,
    },
  });
});
