import { headers } from 'next/headers';
import { getBaseUrl } from '../utils/sitemap';
import citiesData from '@/data/city.json';
import statesData from '@/data/state.json';
import { isRootCity } from '@/lib/rootCity';

// sitemap باید در زمان اجرا (per-request) روی سرور production تولید شود، نه در build.
// در build کانتینر به API دسترسی شبکه ندارد → fetch failed. force-dynamic این را قطعی می‌کند.
export const dynamic = 'force-dynamic';
export const revalidate = 3600;

const MAIN_DOMAIN = 'nobat724.com';
const API_URL = process.env.NEXT_PUBLIC_API_URL;
const PAGE_LIMIT = 500;
const MAX_PAGES = 40;

function toSafeDate(value) {
    if (!value) return null;
    const d = new Date(typeof value === 'number' ? value * 1000 : value);
    return isNaN(d.getTime()) ? null : d;
}

function withLastModified(entry, dateValue) {
    const lastModified = toSafeDate(dateValue);
    return lastModified ? { ...entry, lastModified } : entry;
}

async function getCurrentDomain() {
    try {
        const headersList = await headers();
        return headersList.get('host') || MAIN_DOMAIN;
    } catch {
        return MAIN_DOMAIN;
    }
}

// همان منطق lib/getStateInfo.js — اینجا host را از آرگومان می‌گیریم نه دوباره از headers
function getCityScope(host) {
    const subdomain = (host || '').toLowerCase().replace(/^www\./, '').split('.')[0];
    const matchedCity = citiesData.find(
        (city) => city.domain.split('.')[0] === subdomain
    );
    const matchedState =
        matchedCity && statesData.find((state) => state.id === matchedCity.province_id);
    const isRoot = !matchedCity || isRootCity(matchedCity);
    return { matchedCity, matchedState, isRoot };
}

function getStaticPages(baseUrl) {
    return [
        { url: baseUrl, changeFrequency: 'daily', priority: 1 },
        { url: `${baseUrl}/about-us`, changeFrequency: 'monthly', priority: 0.8 },
        { url: `${baseUrl}/contact-us`, changeFrequency: 'monthly', priority: 0.8 },
        { url: `${baseUrl}/blogs`, changeFrequency: 'weekly', priority: 0.9 },
        { url: `${baseUrl}/doctors`, changeFrequency: 'daily', priority: 0.9 },
        { url: `${baseUrl}/clinics`, changeFrequency: 'daily', priority: 0.9 },
        { url: `${baseUrl}/specialties`, changeFrequency: 'weekly', priority: 0.9 },
    ];
}

async function fetchAllPages(path, extraParams = {}) {
    if (!API_URL) return [];
    const results = [];
    try {
        for (let page = 1; page <= MAX_PAGES; page++) {
            const search = new URLSearchParams({
                ...extraParams,
                page: String(page),
                limit: String(PAGE_LIMIT),
            });
            const res = await fetch(`${API_URL}${path}?${search.toString()}`, {
                next: { revalidate: 3600 },
                signal: AbortSignal.timeout(8000),
            });
            if (!res.ok) break;
            const json = await res.json();
            const raw = json?.data ?? json;
            const items = Array.isArray(raw) ? raw : Array.isArray(raw?.data) ? raw.data : [];
            if (items.length === 0) break;
            results.push(...items);
            const total = json?.meta?.totalRecords;
            if (items.length < PAGE_LIMIT || (total && results.length >= Number(total))) break;
        }
    } catch (error) {
        console.error(`[sitemap] failed to fetch ${path} (page skipped):`, error?.message || error);
    }
    return results;
}

function cityFilterParams(scope) {
    if (scope.isRoot) return {};
    const params = {};
    if (scope.matchedState?.id) params.state_id = String(scope.matchedState.id);
    if (scope.matchedCity?.id) params.city_id = String(scope.matchedCity.id);
    return params;
}

async function getDoctorUrls(baseUrl, scope) {
    const doctors = await fetchAllPages('/api/v1/doctors', cityFilterParams(scope));
    return doctors
        .filter((d) => d?.uuid && d?.owner_status === 'claimed')
        .map((d) =>
            withLastModified(
                {
                    url: `${baseUrl}/doctor/${d.uuid}`,
                    changeFrequency: 'weekly',
                    priority: 0.8,
                },
                d.updated || d.created
            )
        );
}

async function getClinicUrls(baseUrl, scope) {
    const clinics = await fetchAllPages('/api/v1/clinics', cityFilterParams(scope));
    return clinics
        .filter((c) => c?.uuid)
        .map((c) =>
            withLastModified(
                {
                    url: `${baseUrl}/clinic/${c.uuid}`,
                    changeFrequency: 'weekly',
                    priority: 0.7,
                },
                c.updated || c.created
            )
        );
}

async function getBlogUrls(baseUrl) {
    const blogs = await fetchAllPages('/api/v1/blogs');
    return blogs
        .filter((b) => b?.slug || b?.uuid)
        .map((b) =>
            withLastModified(
                {
                    url: `${baseUrl}/blog/${b.slug || b.uuid}`,
                    changeFrequency: 'monthly',
                    priority: 0.6,
                },
                b.updated || b.created
            )
        );
}

export default async function sitemap() {
    try {
        const domain = await getCurrentDomain();
        const baseUrl = getBaseUrl(domain);
        const scope = getCityScope(domain);

        const [doctorUrls, clinicUrls, blogUrls] = await Promise.all([
            getDoctorUrls(baseUrl, scope),
            getClinicUrls(baseUrl, scope),
            // محتوای بلاگ روی همه‌ی دامنه‌ها یکسان است — فقط دامنه‌ی اصلی آن را در sitemap اعلام می‌کند
            scope.isRoot ? getBlogUrls(baseUrl) : Promise.resolve([]),
        ]);

        const allUrls = [...getStaticPages(baseUrl), ...doctorUrls, ...clinicUrls, ...blogUrls];

        const seen = new Set();
        return allUrls.filter((item) => {
            if (seen.has(item.url)) return false;
            seen.add(item.url);
            return true;
        });
    } catch (error) {
        console.error('Error generating sitemap:', error);
        return [];
    }
}
