import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { ValidationError, NotFoundError } from '@server/errors';
import { getStorefrontProfile } from '@server/services/storefront.service';
import { previewRedeem, getSettings } from '@server/services/gift-cards.service';

/**
 * Public preview: a customer can validate a code + see how much would be
 * applied to their cart total before placing the order. No balance change.
 */
export const POST = withErrorHandler(async (req: Request, ctx: RouteContext) => {
  const { restaurantSlug, branchSlug } = await ctx.params;
  const profile = await getStorefrontProfile(restaurantSlug as string, branchSlug as string);
  if (!profile) throw new NotFoundError('Storefront');
  if (!profile.feature_enabled || !profile.branch.storefront_enabled) {
    throw new ValidationError('Storefront is not available');
  }

  const body = await req.json().catch(() => null);
  if (!body) throw new ValidationError('Request body is required');
  const code = String(body.code ?? '').trim();
  const subtotal = Number(body.subtotal ?? 0);
  if (!code) throw new ValidationError('Gift card code is required');
  if (!Number.isFinite(subtotal) || subtotal <= 0) throw new ValidationError('Cart subtotal is required');

  const restaurantId = profile.branch.restaurant_id as string;
  const settings = await getSettings(restaurantId);
  // Compute the actual offsetable amount the same way createStorefrontOrder
  // does — never trust a client-supplied total. Mirror TAX_RATE from
  // storefront.service so preview matches the at-commit application.
  const TAX_RATE = 0.08;
  const tax = Math.round(subtotal * TAX_RATE * 100) / 100;
  const total = Math.round((subtotal + tax) * 100) / 100;
  const offsetable = settings.redemption_rule === 'total' ? total : subtotal;
  const result = await previewRedeem({ restaurantId, code, amountDue: offsetable });
  return NextResponse.json({
    applied: result.applied,
    remaining_balance: result.remaining_balance,
    currency: result.currency,
    redemption_rule: settings.redemption_rule,
  });
});
