#pragma once

#include <string>
#include <memory>
#include <vector>
#include <cstdint>
#include <sqlite3.h>
#include "../shared/protocol/types.h"

namespace scar {

struct UserRecord {
    int id;
    std::string username;
    std::string password_hash;
    std::string salt;
    std::string token;
    UserStatus status;
    std::string role;
    std::string email;
    int64_t last_login;
    std::vector<uint8_t> avatar_pic;
};

class Database {
public:
    explicit Database(const std::string& db_path);
    ~Database();
    
    // Initialize database (create tables if needed)
    bool initialize();
    
    // User operations
    bool createUser(const std::string& username, const std::string& password_hash,
                   const std::string& salt);
    std::unique_ptr<UserRecord> getUserByUsername(const std::string& username);
    bool updateUserToken(const std::string& username, const std::string& token);
    bool updateUserStatus(const std::string& username, UserStatus status);
    bool updateLastLogin(const std::string& username);
    
    // User management
    bool deleteUser(const std::string& username);
    bool updateUserPassword(const std::string& username, const std::string& password_hash,
                           const std::string& salt);
    bool updateUserAvatar(const std::string& username, const std::vector<uint8_t>& avatar_data);
    bool updateUserEmail(const std::string& username, const std::string& email);
    bool updateUserRole(const std::string& username, const std::string& role);
    
    // Query operations
    std::vector<UserRecord> searchUsers(const std::string& field, const std::string& value);
    std::vector<UserRecord> getAllUsers();
    
    // Authentication
    bool verifyCredentials(const std::string& username, const std::string& password_hash);
    
    // Token validation
    std::string getUsernameByToken(const std::string& token);
    
private:
    sqlite3* db_;
    std::string db_path_;
    
    bool execute(const std::string& sql);
};

} // namespace scar
