using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;

namespace MilitaryTrainingManagement.Controllers;

/// <summary>
/// 文件服务控制器
/// </summary>
[ApiController]
[Route("api/files")]
public class FilesController : ControllerBase
{
    private readonly IWebHostEnvironment _environment;
    private readonly FileExtensionContentTypeProvider _contentTypeProvider;

    public FilesController(IWebHostEnvironment environment)
    {
        _environment = environment;
        _contentTypeProvider = new FileExtensionContentTypeProvider();
    }

    /// <summary>
    /// 获取上传的文件
    /// </summary>
    [HttpGet("{*filePath}")]
    [AllowAnonymous]
    public IActionResult GetFile(string filePath)
    {
        if (string.IsNullOrEmpty(filePath))
            return BadRequest(new { message = "文件路径不能为空" });

        // 安全检查：防止路径遍历攻击
        if (filePath.Contains("..") || filePath.Contains("~"))
            return BadRequest(new { message = "无效的文件路径" });

        var uploadsPath = Path.Combine(_environment.ContentRootPath, "uploads");
        var fullPath = Path.Combine(uploadsPath, filePath);

        // 确保文件在uploads目录内
        if (!fullPath.StartsWith(uploadsPath))
            return BadRequest(new { message = "无效的文件路径" });

        if (!System.IO.File.Exists(fullPath))
            return NotFound(new { message = "文件不存在" });

        // 获取文件的MIME类型
        if (!_contentTypeProvider.TryGetContentType(fullPath, out var contentType))
        {
            contentType = "application/octet-stream";
        }

        var fileStream = System.IO.File.OpenRead(fullPath);
        return File(fileStream, contentType);
    }
}
