import type { Game, GameContent } from '@prisma/client';

const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL ?? 'https://gamesji.com';
const SITE_NAME = process.env.NEXT_PUBLIC_SITE_NAME ?? 'GamesJi';

export function buildVideoGameSchema(game: Game & { content: GameContent | null }) {
  return {
    '@context': 'https://schema.org',
    '@type': 'VideoGame',
    name: game.name,
    description: game.content?.metaDescription ?? game.summary ?? undefined,
    url: `${SITE_URL}/games/${game.slug}`,
    image: game.coverUrl ?? undefined,
    datePublished: game.releaseDate ? game.releaseDate.toISOString().slice(0, 10) : undefined,
    genre: game.genres.length ? game.genres : undefined,
    gamePlatform: game.platforms.length ? game.platforms : undefined,
    playMode: game.gameModes.length
      ? game.gameModes.map((m) => (m.toLowerCase().includes('multi') ? 'MultiPlayer' : 'SinglePlayer'))
      : undefined,
    publisher: game.publishers.map((name) => ({ '@type': 'Organization', name })),
    author: game.developers.map((name) => ({ '@type': 'Organization', name })),
    contentRating: game.ageRating ?? undefined,
    aggregateRating:
      game.igdbRating != null && game.igdbRatingCount && game.igdbRatingCount > 0
        ? {
            '@type': 'AggregateRating',
            ratingValue: (game.igdbRating / 20).toFixed(1), // IGDB is 0-100, schema.org expects a 0-5-ish scale by convention
            bestRating: '5',
            worstRating: '0',
            ratingCount: game.igdbRatingCount,
          }
        : undefined,
  };
}

export function buildFaqSchema(faqs: { question: string; answer: string }[]) {
  return {
    '@context': 'https://schema.org',
    '@type': 'FAQPage',
    mainEntity: faqs.map((f) => ({
      '@type': 'Question',
      name: f.question,
      acceptedAnswer: {
        '@type': 'Answer',
        text: f.answer,
      },
    })),
  };
}

export function buildBreadcrumbSchema(items: { name: string; url: string }[]) {
  return {
    '@context': 'https://schema.org',
    '@type': 'BreadcrumbList',
    itemListElement: items.map((item, i) => ({
      '@type': 'ListItem',
      position: i + 1,
      name: item.name,
      item: item.url.startsWith('http') ? item.url : `${SITE_URL}${item.url}`,
    })),
  };
}

export function buildItemListSchema(games: { name: string; slug: string }[]) {
  return {
    '@context': 'https://schema.org',
    '@type': 'ItemList',
    itemListElement: games.map((g, i) => ({
      '@type': 'ListItem',
      position: i + 1,
      url: `${SITE_URL}/games/${g.slug}`,
      name: g.name,
    })),
  };
}

export function buildOrganizationSchema() {
  return {
    '@context': 'https://schema.org',
    '@type': 'Organization',
    name: SITE_NAME,
    url: SITE_URL,
    logo: `${SITE_URL}/logo.png`,
  };
}
