<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\repository\admin;

use app\model\AdminRole;
use app\model\AdminRoleUser;
use app\model\AdminUser;
use app\repository\BaseRepository;
use think\facade\Db;


/**
 * Admin User Repository
 * @package app\repository\admin
 */
class AdminUserRepository extends BaseRepository
{

    /**
     * Find admin user by primary key
     * @param int $id Admin user ID
     * @return AdminUser|null
     */
    public function findById(int $id): ?AdminUser
    {
        $user = AdminUser::find($id);
        return $user instanceof AdminUser ? $user : null;
    }


    /**
     * Find admin user by username
     * @param string $username Admin username
     * @return AdminUser|null
     */
    public function findByUsername(string $username): ?AdminUser
    {
        $user = AdminUser::where('username', $username)->find();
        return $user instanceof AdminUser ? $user : null;
    }


    /**
     * 分页查询管理员
     * @param array $filters
     * @param int $limit
     * @return array
     */
    public function paginate(array $filters, int $limit): array
    {
        $query = AdminUser::order('id', 'desc');
        $keyword = trim((string)($filters['keyword'] ?? ''));
        if ($keyword !== '') {
            $query->where('username|nickname', 'like', "%{$keyword}%");
        }

        return $query->paginate($limit)->toArray();
    }


    /**
     * Persist an admin user record
     * @param AdminUser $user Admin user model instance
     * @return void
     */
    public function save(AdminUser $user): void
    {
        $user->save();
    }


    /**
     * Delete an admin user record
     * @param AdminUser $user Admin user model instance
     * @return void
     */
    public function delete(AdminUser $user): void
    {
        $user->delete();
    }


    /**
     * Remove all role assignments for an admin user
     * @param int $userId Admin user ID
     * @return void
     */
    public function clearRoles(int $userId): void
    {
        AdminRoleUser::where('admin_user_id', $userId)->delete();
    }


    /**
     * Assign roles to an admin user
     * @param int $userId Admin user ID
     * @param array $roleIds List of role IDs to assign
     * @return void
     */
    public function assignRoles(int $userId, array $roleIds): void
    {
        foreach ($roleIds as $roleId) {
            Db::name('sys_admin_role_users')->insert([
                'admin_user_id' => $userId,
                'role_id' => (int)$roleId,
            ]);
        }
    }


    /**
     * Filter role IDs to only those that are active
     * @param array $roleIds Role IDs to check
     * @return array
     */
    public function activeRoleIds(array $roleIds): array
    {
        return array_map('intval', AdminRole::whereIn('id', $roleIds)->where('status', 1)->column('id'));
    }


    /**
     * Get roles grouped by user IDs
     * @param array $userIds Admin user IDs
     * @return array
     */
    public function rolesByUserIds(array $userIds): array
    {
        if (empty($userIds)) {
            return [];
        }

        $pairs = Db::name('sys_admin_role_users')
            ->alias('ru')
            ->leftJoin('sys_admin_roles r', 'ru.role_id = r.id')
            ->whereIn('ru.admin_user_id', $userIds)
            ->field('ru.admin_user_id,r.id as role_id,r.name as role_name,r.code as role_code')
            ->select()
            ->toArray();

        $rolesByUser = [];
        foreach ($pairs as $row) {
            $uid = (int)$row['admin_user_id'];
            if (!isset($rolesByUser[$uid])) {
                $rolesByUser[$uid] = [];
            }
            $rolesByUser[$uid][] = [
                'id' => (int)$row['role_id'],
                'name' => (string)($row['role_name'] ?? ''),
                'code' => (string)($row['role_code'] ?? ''),
            ];
        }

        return $rolesByUser;
    }
}