import { headers } from "next/headers";
import citiesData from "@/data/city.json";

const MAIN_DOMAIN = "https://nobat724.com";

/**
 * Determines if the current domain should have a canonical tag
 * and returns the canonical URL if needed
 */
export function getCanonicalUrl() {
    try {
        const headersList = headers();
        const host = headersList.get("host") || "";
        const pathname = headersList.get("x-pathname") || "/";

        // Normalize host (remove www and convert to lowercase)
        const normalizedHost = host.toLowerCase().replace(/^www\./, "");

        // Check if current domain is the main domain
        if (normalizedHost === "nobat724.com") {
            return null; // No canonical needed for main domain
        }

        // Check if this is a subdomain/different domain from our city data
        const subdomain = normalizedHost.split(".")[0];
        const matchedCity = citiesData.find((city) => {
            const cityDomain = city.domain.toLowerCase();
            return cityDomain.includes(subdomain) || cityDomain === normalizedHost;
        });

        // If we found a matching city or any non-main domain, canonicalize to main domain
        if (matchedCity || normalizedHost !== "nobat724.com") {
            // Ensure pathname starts with /
            const cleanPathname = pathname.startsWith("/") ? pathname : `/${pathname}`;
            return `${MAIN_DOMAIN}${cleanPathname}`;
        }

        return null;
    } catch (error) {
        console.error("Error generating canonical URL:", error);
        return null;
    }
}

/**
 * Client-side version for dynamic routes or client components
 */
export function getCanonicalUrlClient() {
    if (typeof window === "undefined") return null;

    try {
        const host = window.location.host;
        const pathname = window.location.pathname;

        // Normalize host (remove www and convert to lowercase)
        const normalizedHost = host.toLowerCase().replace(/^www\./, "");

        // Check if current domain is the main domain
        if (normalizedHost === "nobat724.com") {
            return null; // No canonical needed for main domain
        }

        // Check if this is a subdomain/different domain from our city data
        const subdomain = normalizedHost.split(".")[0];
        const matchedCity = citiesData.find((city) => {
            const cityDomain = city.domain.toLowerCase();
            return cityDomain.includes(subdomain) || cityDomain === normalizedHost;
        });

        // If we found a matching city or any non-main domain, canonicalize to main domain
        if (matchedCity || normalizedHost !== "nobat724.com") {
            return `${MAIN_DOMAIN}${pathname}`;
        }

        return null;
    } catch (error) {
        console.error("Error generating client canonical URL:", error);
        return null;
    }
}