using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;

namespace server.Controllers;

/// <summary>
/// 数据控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class DataController : ControllerBase
{
    private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

    /// <summary>
    /// 创建数据库表
    /// </summary>
    /// <returns>插入的记录数</returns>
    [EnableCors("Development")]
    [HttpPost("CreateTable")]
    public IResult CreateTables()
    {
        using var db = new Database.AppDataConnection();
        db.CreateAllTables();
        return TypedResults.Ok();
    }

    /// <summary>
    /// 删除数据库表
    /// </summary>
    /// <returns>插入的记录数</returns>
    [EnableCors("Development")]
    [HttpDelete("DropTables")]
    public IResult DropTables()
    {
        using var db = new Database.AppDataConnection();
        db.DropAllTables();
        return TypedResults.Ok();
    }

    /// <summary>
    /// 获取所有用户
    /// </summary>
    /// <returns>用户列表</returns>
    [HttpGet("AllUsers")]
    public IResult AllUsers()
    {
        using var db = new Database.AppDataConnection();
        var ret = db.User.ToList();
        return TypedResults.Ok(ret);
    }

    /// <summary>
    /// 注册新用户
    /// </summary>
    /// <param name="name">用户名</param>
    /// <returns>操作结果</returns>
    [HttpPost("SignUpUser")]
    public IResult SignUpUser(string name)
    {
        if (name.Length > 255)
            return TypedResults.BadRequest("Name Couln't over 255 characters");

        using var db = new Database.AppDataConnection();
        var ret = db.AddUser(name);
        return TypedResults.Ok(ret);
    }
}

