import { FastifyReply, FastifyRequest } from 'fastify';

import { config } from '../config';

/** Paths that must hit our handlers (trailing slash), not upstream SPA. */
const REDIRECTS: Array<{ match: (path: string) => boolean; target: string }> = [
  {
    match: (p) => p === '/pl/pl/checkout/cart',
    target: config.intercept.cartPagePath,
  },
  {
    match: (p) => p === '/pl/pl/checkout/order',
    target: config.intercept.checkoutOrderPath,
  },
  {
    match: (p) => p === '/pl/pl/checkout/order/created',
    target: config.intercept.checkoutOrderCreatedPath,
  },
  {
    match: (p) => p === '/pl/pl/checkout/order/error',
    target: config.intercept.checkoutOrderErrorPath,
  },
];

export function checkoutPathRedirectTarget(pathOnly: string): string | null {
  for (const rule of REDIRECTS) {
    if (rule.match(pathOnly)) return rule.target;
  }
  return null;
}

export async function handleCheckoutPathRedirect(
  request: FastifyRequest,
  reply: FastifyReply,
): Promise<void> {
  const pathOnly = request.url.split('?')[0] || '/';
  const target = checkoutPathRedirectTarget(pathOnly);
  if (!target) {
    reply.status(404).send('Not found');
    return;
  }
  const query = request.url.includes('?') ? request.url.slice(request.url.indexOf('?')) : '';
  reply.redirect(`${target}${query}`, 301);
}
