using System.IO;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;

namespace server.Controllers;

/// <summary>
/// 教程 API
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class TutorialController : ControllerBase
{
    private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
    private readonly IWebHostEnvironment _environment;

    /// <summary>
    /// [TODO:description]
    /// </summary>
    /// <param name="environment">[TODO:parameter]</param>
    /// <returns>[TODO:return]</returns>
    public TutorialController(IWebHostEnvironment environment)
    {
        _environment = environment;
    }

    /// <summary>
    /// 获取所有可用的教程目录
    /// </summary>
    /// <returns>教程目录列表</returns>
    [HttpGet]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status500InternalServerError)]
    public IActionResult GetTutorials()
    {
        try
        {
            // 获取文档目录
            string docPath = Path.Combine(_environment.WebRootPath, "doc");
            
            if (!Directory.Exists(docPath))
            {
                return Ok(new { tutorials = new List<string>() });
            }

            // 获取所有子目录
            var directories = Directory.GetDirectories(docPath)
                .Select(Path.GetFileName)
                .Where(dir => !string.IsNullOrEmpty(dir))
                .ToList();

            return Ok(new { tutorials = directories });
        }
        catch (Exception ex)
        {
            logger.Error(ex, "获取教程目录失败");
            return StatusCode(500, new { error = "无法读取教程目录" });
        }
    }
}
