import { seoCities } from "@/data/seo/cities";
import { seoSegments } from "@/data/seo/segments";
import { seoServices } from "@/data/seo/services";
import type { SeoPageContext } from "./types";
import {
  buildSegmentCitySlug,
  buildSegmentSlug,
  buildServiceCitySlug,
  buildServiceSegmentCitySlug,
} from "./slugs";

export interface RelatedLink {
  href: string;
  label: string;
}

export function getRelatedPages(ctx: SeoPageContext, limit = 12): RelatedLink[] {
  const links: RelatedLink[] = [];
  const seen = new Set<string>([ctx.slug]);

  const push = (slug: string, label: string) => {
    if (seen.has(slug) || links.length >= limit) return;
    seen.add(slug);
    links.push({ href: `/${slug}`, label });
  };

  if (ctx.city) {
    for (const near of ctx.city.nearbySlugs) {
      const c = seoCities.find((x) => x.slug === near);
      if (!c) continue;
      if (ctx.service) {
        push(
          buildServiceCitySlug(ctx.service.slug, c.slug),
          `${ctx.service.name} em ${c.name}`,
        );
      }
      if (ctx.segment) {
        push(
          buildSegmentCitySlug(ctx.segment.slug, c.slug),
          `App para ${ctx.segment.name} em ${c.name}`,
        );
      }
    }
    if (ctx.service && ctx.segment) {
      for (const seg of seoSegments
        .filter((s) => ctx.segment!.relatedSlugs.includes(s.slug))
        .slice(0, 3)) {
        push(
          buildServiceSegmentCitySlug(ctx.service.slug, seg.slug, ctx.city.slug),
          `${ctx.service.name} para ${seg.name} em ${ctx.city.name}`,
        );
      }
    }
  }

  if (ctx.segment && !ctx.city) {
    for (const seg of seoSegments
      .filter((s) => ctx.segment!.relatedSlugs.includes(s.slug))
      .slice(0, 4)) {
      push(buildSegmentSlug(seg.slug), `App para ${seg.name}`);
    }
  }

  if (ctx.service && ctx.city && !ctx.segment) {
    for (const svc of seoServices.filter((s) => s.slug !== ctx.service!.slug).slice(0, 4)) {
      push(
        buildServiceCitySlug(svc.slug, ctx.city!.slug),
        `${svc.name} em ${ctx.city!.name}`,
      );
    }
    for (const seg of seoSegments.slice(0, 4)) {
      push(
        buildServiceSegmentCitySlug(ctx.service.slug, seg.slug, ctx.city.slug),
        `${ctx.service.name} para ${seg.name}`,
      );
    }
  }

  return links;
}

export function getClusterLinks(ctx: SeoPageContext): RelatedLink[] {
  const links: RelatedLink[] = [];

  if (ctx.service) {
    links.push({
      href: `/app/${ctx.service.slug}/${ctx.city?.slug ?? ctx.state?.slug ?? ""}`,
      label: `Rota estruturada: ${ctx.service.name}`,
    });
  }
  if (ctx.segment && ctx.city) {
    links.push({
      href: `/app/segmento/${ctx.segment.slug}/${ctx.city.slug}`,
      label: `Segmento em ${ctx.city.name}`,
    });
  }

  return links.filter((l) => !l.href.endsWith("/"));
}
