import jwt from 'jsonwebtoken';
import { IUserRecord, UserDb } from '../db/users.mjs';

const secretKey = 'your-secret-key'; //JWT key

const db = new UserDb();

export class UserServices {
    /**
     * signup
     */
    async signup(username: string, password: string): Promise<IUserRecord> {
        const user = await db.get(username);
        if (user) {
            throw 'Username already exists';
        }

        return await db.insert(username, password);
    }

    /**
     * login
     */
    async login(username: string, password: string): Promise<string> {
        const row = await db.get(username);
        if (!row || row.password !== password) {
            throw 'Invalid username or password';
        }

        // JWT Token
        return jwt.sign({ username: row.username, id: row.id }, secretKey);
    }

    async get(userId: string): Promise<IUserRecord | undefined> {
        const row = await db.getById(userId);
        return row;
    }

    async getByName(name: string): Promise<IUserRecord | undefined> {
        return await db.get(name);
    }

    /**
     * verify token
     */
    async verifyToken (token: string) {
        // 验证 JWT Token
        const d = jwt.verify(token, secretKey) as { id: string };

        const user = await db.getById(d.id);

        return user;
    }

    async search(key: string) {
        let users = await db.all();
        if (key) {
            key = key.toLowerCase();
            users = users.filter((u) => u.username.toLowerCase().includes(key));
        }
        return users;
    }
}
