import type { DealType } from '@/lib/deal-types';

export interface ParsedDealsPath {
  type?: DealType;
  catSlug?: string;
  tagSlugs: string[];
  page: number;
  canonical: string;
}

const PAGE_RE = /^page-(\d+)$/;
const TYPE_MAP: Record<string, DealType> = { coupon: 'COUPON', group: 'GROUP', item: 'ITEM' };

export function parseDealsPath(rawPath: string): ParsedDealsPath | null {
  const segments = rawPath.split('/').filter((s) => s.length > 0);

  if (segments[0] === 'all') segments.shift();

  let type: DealType | undefined;
  let catSlug: string | undefined;
  let tagSlugs: string[] = [];
  let page = 1;

  if (segments[0] && TYPE_MAP[segments[0]]) {
    type = TYPE_MAP[segments[0]];
    segments.shift();
  }

  function tryConsumeTrailingPage(): void {
    const last = segments[segments.length - 1];
    if (!last) return;
    const m = PAGE_RE.exec(last);
    if (m) {
      page = parseInt(m[1]!, 10);
      segments.pop();
    }
  }

  if (segments[0]) {
    if (segments[0] === '-') {
      catSlug = undefined;
      segments.shift();
    } else if (!PAGE_RE.test(segments[0])) {
      catSlug = segments[0];
      segments.shift();
    }
  }

  if (segments[0] && !PAGE_RE.test(segments[0])) {
    tagSlugs = segments[0].split(',').filter((s) => s.length > 0);
    segments.shift();
  }

  tryConsumeTrailingPage();

  if (segments.length > 0) return null;

  const sortedTags = [...tagSlugs].sort();
  const parts: string[] = [];
  if (type === 'COUPON') parts.push('coupon');
  else if (type === 'GROUP') parts.push('group');
  else if (type === 'ITEM') parts.push('item');
  if (catSlug) parts.push(catSlug);
  else if (sortedTags.length > 0) parts.push('-');
  if (sortedTags.length > 0) parts.push(sortedTags.join(','));
  if (page > 1) parts.push(`page-${page}`);
  const canonical = parts.join('/');

  return { type, catSlug, tagSlugs: sortedTags, page, canonical };
}
