const axios = require('axios');
const {cleanEntry} = require(`../../../src/libs/entry`);
//const apiServer = 'http://10.1.254.11:3100';
const apiServer = 'http://localhost:3100';

const get = async (config, opts) => {
  let articleId;
  let match;
  if  ( match = opts.pathname.match(/\/(\d+)$/) ) {
    articleId = parseInt(match[1]);
  } else
  if  ( match = opts.pathname.match(/\/(\d+).html$/) ) {
    articleId = parseInt(match[1]);
  }
  //console.log({articleId});
  const externalApiUrl = `${apiServer}/api/entry/${articleId}`;
  let entryContent = null;
  let recentEntries = [];
  let allTags = [];

  try {
    // 記事詳細の取得
    const response = await axios.get(externalApiUrl);
    if (response) {
      if (response.data) {
        entryContent = cleanEntry(response.data);
      }
    } else {
      console.error(`Failed to fetch article content for ID ${articleId}: ${response.status} ${response.statusText}`);
    }

    // 最近の記事の取得 (サイドバー表示用)
    // per_page=20 で取得して、現在の記事を除外してから上位5件を表示する
    const recentResponse = await axios.get(`${apiServer}/api/entries/?page_name=blog,hieronymus&tags=Hieronymus&per_page=20`);
    if (recentResponse) {
      let allEntries = recentResponse.data;
      // 現在表示している記事を除外して、最大5件を取得
      recentEntries = allEntries.filter(entry => entry.id != articleId).slice(0, 5);
    } else {
      console.error(`Failed to fetch recent entries: ${recentResponse.status}`);
    }

    // タグ一覧の取得 (サイドバー表示用)
    const tagsResponse = await axios.get(`${apiServer}/api/tags?page_name=blog,hieronymus`);
    if (tagsResponse) {
      allTags = tagsResponse.data;
    } else {
      console.error(`Failed to fetch tags: ${tagsResponse.status}`);
    }


  } catch (error) {
    console.error(`Error fetching article content for ID ${articleId}:`, error);
  }

  if (!entryContent) {
    return res.status(404).render('404', { title: '記事が見つかりません', message: '指定された記事は見つかりませんでした。' });
  }

  // 記事コンテンツからメタデータを生成
  const title = entryContent.title ? `${entryContent.title} | Hieronymus ブログ` : '記事タイトル | Hieronymus ブログ';
  const description = entryContent.head || entryContent.description || '記事の概要をここに記述します。';
  const og_url = `https://hieronymus.beesnest-inc.com/blog/${articleId}`;
  const og_image = entryContent.thumbnailId ? `https://hieronymus.beesnest-inc.com/api/media/${entryContent.thumbnailId}` : null;

  return  ({
    filename: '/assets/templates/article.ejs',
    data: {
      title: title,
      description: description,
      og_title: title,
      og_description: description,
      og_url: og_url,
      og_image: og_image,
      twitter_title: title,
      twitter_description: description,
      current_page: 'blog',
      entryContent: entryContent,
      recentEntries: recentEntries, // 追加: 最近の記事リスト
      allTags: allTags // 追加: タグ一覧
    }
  })
}

module.exports = {
    get: get
}

