using BCrypt.Net;
using Model; // 确保添加了这行 using
using System;
using System.Data.SQLite;
using StandardLibrary;
public class UserService
{
    // 注意：Users 表现在不需要单独的 Salt 列了！
    // Password 列应足够长（如 TEXT 或 VARCHAR(255)），因为 BCrypt 哈希很长。

    public static bool ValidateUser(User user,out string err)
    {
        using (var connection = new SQLiteConnection(DatabaseHelper.ConnectionString))
        {
            connection.Open();

            using (var command = new SQLiteCommand(
                "SELECT Id,PasswordHash,PermissionLevel,CanCloseSoftware FROM Users WHERE Username = @username",
                connection))
            {
                command.Parameters.AddWithValue("@username", user.Username);
                using (var reader = command.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        int id = reader.GetInt32(0);
                        string storedHash = reader.GetString(1);
                        int permissionLevel = reader.GetInt32(2);
                        bool canClose = reader.GetBoolean(3);

                        // 使用 BCrypt.Verify 进行验证
                        if (BCrypt.Net.BCrypt.Verify(user.Password, storedHash))
                        {
                            user.Id = id;
                            user.PermissionLevel = EnumExt.TryParseEnum<PermissionLevel>(permissionLevel, out PermissionLevel result)? result:PermissionLevel.无权限;
                            user.Password = string.Empty;
                            user.CanCloseSoftware = canClose;
                            err = string.Empty;
                            return true;
                        }
                        else
                        {
                            err = "密码错误";
                            return false;
                        }
                    }
                }
            }
        }
        err = "用户不存在";
        return false;
    }

    public static bool RegisterUser(User user,out string err)//string username, string password, int permissionLevel
    {
        // 步骤 1：检查用户名是否已存在
        if (IsUsernameExists(user.Username))
        {
            // 用户名已存在，返回 false 表示注册失败
            err = "用户已存在";
            return false;
        }

        // 步骤 2：用户名不存在，可以安全注册
        string passwordHash = BCrypt.Net.BCrypt.HashPassword(user.Password);

        using (var connection = new SQLiteConnection(DatabaseHelper.ConnectionString))
        {
            connection.Open();

            using (var command = new SQLiteCommand(
                "INSERT INTO Users (Username, PasswordHash, PermissionLevel,CanCloseSoftware) VALUES (@username, @hash, @level,@canClose)",
                connection))
            {
                command.Parameters.AddWithValue("@username", user.Username);
                command.Parameters.AddWithValue("@hash", passwordHash);
                command.Parameters.AddWithValue("@level", user.PermissionLevel);
                command.Parameters.AddWithValue("@canClose", user.CanCloseSoftware);
                command.ExecuteNonQuery();
            }
        }

        // 注册成功
        err = string.Empty;
        return true;
    }

    // 辅助方法：检查用户名是否存在
    private static bool IsUsernameExists(string username)
    {
        using (var connection = new SQLiteConnection(DatabaseHelper.ConnectionString))
        {
            connection.Open();

            using (var command = new SQLiteCommand(
                "SELECT 1 FROM Users WHERE Username = @username", // SELECT 1 是个技巧，只关心是否存在
                connection))
            {
                command.Parameters.AddWithValue("@username", username);

                // ExecuteScalar() 返回第一行第一列的值，如果不存在则返回 null
                return command.ExecuteScalar() != null;
            }
        }
    }
}