import { MetadataRoute } from 'next';

import { getCreationList } from '@/services/creations';
import { getCreatorList } from '@/services/creators';
import { getAllNews } from '@/services/news';

import { metaAttributes110 } from '@/utils/filterUtils';

export const revalidate = 86400; // 24 hrs cache

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const isTest = process.env.NEXT_PUBLIC_ENV === 'test';
  if (isTest) {
    console.log('🗺️ Skipping sitemap generation in test environment.');
    return [];
  }

  const baseUrl = 'https://azopus.hu';

  console.log('🗺️ Generating sitemap...');

  const sitemap: MetadataRoute.Sitemap = [
    // main route
    {
      url: baseUrl,
      lastModified: new Date(),
      changeFrequency: 'daily',
      priority: 1,
    },

    // static pages
    {
      url: `${baseUrl}/alkotasok`,
      lastModified: new Date(),
      changeFrequency: 'weekly',
      priority: 0.8,
    },
    {
      url: `${baseUrl}/alkotok`,
      lastModified: new Date(),
      changeFrequency: 'monthly',
      priority: 0.5,
    },
    {
      url: `${baseUrl}/alkotok-aktualis-programokkal`,
      lastModified: new Date(),
      changeFrequency: 'daily',
      priority: 0.9,
    },
    // {
    //   url: `${baseUrl}/hirek`,
    //   lastModified: new Date(),
    //   changeFrequency: "daily",
    //   priority: 0.7,
    // },
    {
      url: `${baseUrl}/programok`,
      lastModified: new Date(),
      changeFrequency: 'daily',
      priority: 0.9,
    },
    {
      url: `${baseUrl}/terkep`,
      lastModified: new Date(),
      changeFrequency: 'weekly',
      priority: 0.6,
    },
    {
      url: `${baseUrl}/parhuzamos-eletutak`,
      lastModified: new Date(),
      changeFrequency: 'monthly',
      priority: 0.5,
    },
    {
      url: `${baseUrl}/videok`,
      lastModified: new Date(),
      changeFrequency: 'weekly',
      priority: 0.7,
    },
    {
      url: `${baseUrl}/kereses`,
      lastModified: new Date(),
      changeFrequency: 'yearly',
      priority: 0.3,
    },

    // legal pages
    {
      url: `${baseUrl}/impresszum`,
      lastModified: new Date(),
      changeFrequency: 'yearly',
      priority: 0.2,
    },
    {
      url: `${baseUrl}/adatkezelesi-tajekoztato`,
      lastModified: new Date(),
      changeFrequency: 'yearly',
      priority: 0.2,
    },
    {
      url: `${baseUrl}/sutitajekoztato`,
      lastModified: new Date(),
      changeFrequency: 'yearly',
      priority: 0.2,
    },
    {
      url: `${baseUrl}/szerzoi-jogok`,
      lastModified: new Date(),
      changeFrequency: 'yearly',
      priority: 0.2,
    },
    {
      url: `${baseUrl}/projekt-jellemzoi`,
      lastModified: new Date(),
      changeFrequency: 'yearly',
      priority: 0.2,
    },
    {
      url: `${baseUrl}/oldal-mukodese`,
      lastModified: new Date(),
      changeFrequency: 'yearly',
      priority: 0.2,
    },
  ];

  // category pages - creations
  console.log('📚 Adding category creation pages...');
  for (const category of metaAttributes110) {
    sitemap.push({
      url: `${baseUrl}/alkotasok/${category.prettyKey}`,
      lastModified: new Date(),
      changeFrequency: 'weekly',
      priority: 0.5,
    });
  }

  // category pages - creators
  console.log('👥 Adding category creator pages...');
  for (const category of metaAttributes110) {
    sitemap.push({
      url: `${baseUrl}/alkotok/${category.prettyKey}`,
      lastModified: new Date(),
      changeFrequency: 'weekly',
      priority: 0.8,
    });
  }

  // category pages - map
  console.log('🗺️ Adding category map pages...');
  for (const category of metaAttributes110) {
    sitemap.push({
      url: `${baseUrl}/terkep/${category.prettyKey}`,
      lastModified: new Date(),
      changeFrequency: 'monthly',
      priority: 0.5,
    });
  }

  // category pages - videos
  console.log('🎥 Adding category video pages...');
  for (const category of metaAttributes110) {
    sitemap.push({
      url: `${baseUrl}/videok/${category.prettyKey}`,
      lastModified: new Date(),
      changeFrequency: 'weekly',
      priority: 0.6,
    });
  }

  // API calls to fetch dynamic data
  const apiCalls = [getCreationList(), getCreatorList(), getAllNews()];

  const [creationsResult, creatorsResult, newsResult] = await Promise.allSettled(apiCalls);

  // all creations
  if (creationsResult.status === 'fulfilled' && creationsResult.value) {
    const totalCreations = creationsResult.value.length;
    console.log(`🎨 Adding ${totalCreations} creations...`);

    // Warn if dataset is unexpectedly large
    if (totalCreations > 50000) {
      console.warn(`⚠️ Large dataset: ${totalCreations} creations. Consider pagination.`);
    }

    for (const creation of creationsResult.value) {
      if (creation.alkotasAzonosito) {
        sitemap.push({
          url: `${baseUrl}/alkotas/${creation.alkotasAzonosito}`,
          // temporary add new Date() for re-crawling after migration
          // lastModified: creation.modositasIdeje
          //   ? new Date(creation.modositasIdeje)
          //   : new Date(creation.letrehozasIdeje || Date.now()),
          lastModified: new Date(),
          changeFrequency: 'monthly',
          priority: 0.6,
        });
      }
    }
  } else {
    console.error(
      '❌ Failed to fetch creations:',
      creationsResult.status === 'rejected' ? creationsResult.reason : 'No data'
    );
  }

  // all creators
  if (creatorsResult.status === 'fulfilled' && creatorsResult.value) {
    console.log(`👨‍🎨 Adding ${creatorsResult.value.length} creators...`);

    for (const creator of creatorsResult.value) {
      if (creator.alkotoAzonosito) {
        // Main creator page
        sitemap.push({
          url: `${baseUrl}/alkoto/${creator.alkotoAzonosito}`,
          // temporary add new Date() for re-crawling after migration
          // lastModified: creator.modositasIdeje
          //   ? new Date(creator.modositasIdeje)
          //   : new Date(creator.letrehozasIdeje || Date.now()),
          lastModified: new Date(),
          changeFrequency: 'weekly',
          priority: 0.9,
        });

        // Creator section pages
        if (creator.hasCreations) {
          sitemap.push({
            url: `${baseUrl}/alkoto/${creator.alkotoAzonosito}/alkotasok`,
            lastModified: new Date(),
            changeFrequency: 'monthly',
            priority: 0.7,
          });
        }

        if (creator.hasLifeEvents) {
          sitemap.push({
            url: `${baseUrl}/alkoto/${creator.alkotoAzonosito}/eletut-esemenyek`,
            lastModified: new Date(),
            changeFrequency: 'monthly',
            priority: 0.7,
          });
        }

        if (creator.hasNews) {
          sitemap.push({
            url: `${baseUrl}/alkoto/${creator.alkotoAzonosito}/mma-hirek`,
            lastModified: new Date(),
            changeFrequency: 'monthly',
            priority: 0.6,
          });
        }

        if (creator.hasCreationVideos) {
          sitemap.push({
            url: `${baseUrl}/alkoto/${creator.alkotoAzonosito}/alkotas-videok`,
            lastModified: new Date(),
            changeFrequency: 'monthly',
            priority: 0.6,
          });
        }
      }
    }
  } else {
    console.error(
      '❌ Failed to fetch creators:',
      creatorsResult.status === 'rejected' ? creatorsResult.reason : 'No data'
    );
  }

  // all news
  if (newsResult.status === 'fulfilled' && newsResult.value) {
    console.log(`📰 Adding ${newsResult.value.length} news articles...`);

    for (const newsItem of newsResult.value) {
      if (newsItem.id) {
        sitemap.push({
          url: `${baseUrl}/hir/${newsItem.id}`,
          lastModified: newsItem.megjelenesIdejes
            ? new Date(newsItem.megjelenesIdejes)
            : new Date(),
          changeFrequency: 'daily',
          priority: 0.4,
        });
      }
    }
  } else {
    console.error(
      '❌ Failed to fetch news:',
      newsResult.status === 'rejected' ? newsResult.reason : 'No data'
    );
  }

  // sort sitemap by priority
  const sortedSitemap = sitemap.sort((a, b) => (b.priority || 0) - (a.priority || 0));

  console.log(`✅ Sitemap ready! Total: ${sortedSitemap.length} URLs`);

  return sortedSitemap;
}
