/**
 * 系统用户数据模型
 * 作者: 阿瑞
 * 功能: 提供系统用户相关的数据访问方法
 * 版本: 1.4
 */

import { NextResponse, NextRequest } from 'next/server';
import { connectSystemDB, RequestWithDB } from '@/lib/db';
import { ISystemUser } from './types';

/**
 * MySQL查询结果行类型
 */
interface MySQLRow {
    [key: string]: string | number | boolean | Date | null;
}

/**
 * 模拟请求对象类型
 */
interface MockRequest {
    headers: {
        get: (name: string) => string | null;
    };
    json: () => Promise<Record<string, unknown>>;
}

/**
 * 工作空间成员类型
 */
interface WorkspaceMember {
    id: number;
    username: string;
    email: string;
    phone: string | null;
    roleType: string;
    roleName: string | null;
    isCustomRole: boolean;
    status: number;
    lastLoginAt: string | null;
    createdAt: string | null;
}

/**
 * API响应类型
 */
interface ApiResponse {
    success: boolean;
    data?: unknown;
    error?: string;
}

/**
 * 系统用户模型
 * 提供用户相关数据操作函数
 */
export class SystemUserModel {
    /**
     * 创建模拟请求对象
     * @returns 模拟的请求对象
     */
    private static createMockRequest(): MockRequest {
        return {
            headers: { get: () => null },
            json: async () => ({})
        };
    }

    /**
     * 处理数据库查询结果并返回响应
     * @param mockReq 模拟请求对象
     * @param wrappedHandler 包装的处理函数
     * @returns 解析后的响应数据
     */
    private static async processDbRequest<T>(
        mockReq: MockRequest,
        wrappedHandler: (req: NextRequest) => Promise<Response>
    ): Promise<T | null> {
        const response = await wrappedHandler(mockReq as unknown as NextRequest);
        const data = await response.json() as ApiResponse;
        return data.success && data.data ? data.data as T : null;
    }

    /**
     * 根据用户名查找用户
     * @param username 用户名
     * @returns 用户对象或null
     */
    static async getByUsername(username: string): Promise<ISystemUser | null> {
        try {
            // 创建一个符合API规范的处理函数
            const handler = async (req: RequestWithDB) => {
                const [rows] = await req.db.query(
                    'SELECT * FROM system_users WHERE username = ?',
                    [username]
                );

                const users = rows as MySQLRow[];
                // 返回用户数据，而不是NextResponse
                return NextResponse.json({
                    success: true,
                    data: users.length > 0 ? users[0] : null
                });
            };

            // 使用系统数据库连接
            const wrappedHandler = connectSystemDB(handler);

            // 执行处理函数并处理响应
            return this.processDbRequest<ISystemUser>(
                this.createMockRequest(),
                wrappedHandler
            );
        } catch (error) {
            console.error('获取用户失败:', error);
            return null;
        }
    }

    /**
     * 根据邮箱查找用户
     * @param email 邮箱地址
     * @returns 用户对象或null
     */
    static async getByEmail(email: string): Promise<ISystemUser | null> {
        try {
            const handler = async (req: RequestWithDB) => {
                const [rows] = await req.db.query(
                    'SELECT * FROM system_users WHERE email = ?',
                    [email]
                );

                const users = rows as MySQLRow[];
                return NextResponse.json({
                    success: true,
                    data: users.length > 0 ? users[0] : null
                });
            };

            const wrappedHandler = connectSystemDB(handler);

            // 执行处理函数并处理响应
            return this.processDbRequest<ISystemUser>(
                this.createMockRequest(),
                wrappedHandler
            );
        } catch (error) {
            console.error('获取用户失败:', error);
            return null;
        }
    }

    /**
     * 根据ID查找用户
     * @param id 用户ID
     * @returns 用户对象或null
     */
    static async getById(id: number): Promise<ISystemUser | null> {
        try {
            const handler = async (req: RequestWithDB) => {
                const [rows] = await req.db.query(
                    'SELECT * FROM system_users WHERE id = ?',
                    [id]
                );

                const users = rows as MySQLRow[];
                return NextResponse.json({
                    success: true,
                    data: users.length > 0 ? users[0] : null
                });
            };

            const wrappedHandler = connectSystemDB(handler);

            // 执行处理函数并处理响应
            return this.processDbRequest<ISystemUser>(
                this.createMockRequest(),
                wrappedHandler
            );
        } catch (error) {
            console.error('获取用户失败:', error);
            return null;
        }
    }

    /**
     * 更新用户最后登录时间
     * @param userId 用户ID
     */
    static async updateLastLogin(userId: number): Promise<boolean> {
        try {
            const handler = async (req: RequestWithDB) => {
                await req.db.query(
                    'UPDATE system_users SET last_login_at = NOW() WHERE id = ?',
                    [userId]
                );

                // 返回成功响应
                return NextResponse.json({
                    success: true
                });
            };

            const wrappedHandler = connectSystemDB(handler);

            // 执行处理函数，模拟请求
            const mockReq = this.createMockRequest();

            const response = await wrappedHandler(mockReq as unknown as NextRequest);
            const data = await response.json() as ApiResponse;

            return data.success === true;
        } catch (error) {
            console.error('更新用户登录时间失败:', error);
            return false;
        }
    }

    /**
     * 获取工作空间成员列表
     * @param workspaceId 工作空间ID
     * @returns 成员列表数组
     */
    static async getWorkspaceMembers(workspaceId: number | string): Promise<WorkspaceMember[]> {
        try {
            const handler = async (req: RequestWithDB) => {
                const [rows] = await req.db.query(
                    `SELECT 
            id, 
            username, 
            email, 
            phone, 
            role_type as roleType, 
            role_name as roleName,
            is_custom_role as isCustomRole,
            status, 
            last_login_at as lastLoginAt, 
            created_at as createdAt
           FROM system_users 
           WHERE workspace_id = ?
           ORDER BY role_type DESC, username ASC`,
                    [workspaceId]
                );

                // 转换为普通JavaScript对象
                const members = JSON.parse(JSON.stringify(rows));

                return NextResponse.json({
                    success: true,
                    data: members
                });
            };

            const wrappedHandler = connectSystemDB(handler);

            // 执行处理函数，模拟请求
            const mockReq = this.createMockRequest();

            const response = await wrappedHandler(mockReq as unknown as NextRequest);
            const data = await response.json() as ApiResponse;

            // 从响应中提取成员数据
            return data.success && data.data ? data.data as WorkspaceMember[] : [];
        } catch (error) {
            console.error('获取工作空间成员失败:', error);
            return [];
        }
    }
} 