<?php

class HVAC_Test_User_Factory {
    private static $personas = [];

    public static function define_persona($name, $config) {
        self::$personas[$name] = $config;
    }

    public static function create_user($config) {
        $defaults = [
            'username' => 'testuser_' . uniqid(),
            'email' => null,
            'password' => 'password',
            'roles' => [],
            'meta' => [],
            'persona' => null
        ];

        $config = wp_parse_args($config, $defaults);

        // Apply persona if specified
        if ($config['persona'] && isset(self::$personas[$config['persona']])) {
            $persona = self::$personas[$config['persona']];
            $config['roles'] = array_merge($config['roles'], $persona['roles'] ?? []);
            $config['meta'] = array_merge($config['meta'], $persona['meta'] ?? []);
        }

        // Create user
        $user_id = wp_insert_user([
            'user_login' => $config['username'],
            'user_pass' => $config['password'],
            'user_email' => $config['email'] ?? ($config['username'] . '@example.com')
        ]);

        if (is_wp_error($user_id)) {
            return $user_id;
        }

        $user = new WP_User($user_id);

        // Assign roles
        foreach ($config['roles'] as $role) {
            if (!HVAC_Role_Manager::role_exists($role)) {
                HVAC_Role_Manager::create_role($role);
            }
            $user->add_role($role);
        }

        // Add meta
        foreach ($config['meta'] as $key => $value) {
            update_user_meta($user_id, $key, $value);
        }

        return $user;
    }

    public static function cleanup_user($user_id) {
        $user = get_user_by('id', $user_id);
        if (!$user) {
            return;
        }

        // Clean up roles if they're no longer used
        foreach ($user->roles as $role) {
            $users_with_role = get_users([
                'role' => $role,
                'fields' => 'ids',
                'exclude' => [$user_id]
            ]);

            if (empty($users_with_role)) {
                HVAC_Role_Manager::delete_role($role);
            }
        }

        // Delete the user
        wp_delete_user($user_id);
    }
}