import { query } from "../sql/query"; // 确保路径是正确的

class UserModel {
    //检查账户是否存在
    async checkAccountIsExist(uid: any, channel_id: any) {
        return await query(`SELECT * FROM accounts where account = ? and channel_id = ?`, [uid, channel_id]);
    }

    //创建账户
    async createAccount(
        uid: any,
        channel_id: any,
        reg_ip: any,
        device_no: any,
        reg_device: any,
        create_time: string,
        platform:  string,
    ) {
        return await query(
            `INSERT INTO accounts(account,status,channel_id,reg_ip,device_no,reg_device,platform,created_at, updated_at) VALUES(?,1,?,?,?,?,?,?,?)`,
            [uid, channel_id, reg_ip, device_no, reg_device, platform, create_time, create_time]
        );
    }

    //根据ip和device_no查询platform值
    async getPlatformByIpAndDevice(ip: string, device_no: string) {
        const rows = await query(
            `SELECT platform FROM accounts WHERE reg_ip = ? AND device_no = ? AND platform IS NOT NULL AND platform != '' ORDER BY created_at DESC LIMIT 1`,
            [ip, device_no]
        );
        return rows[0]?.platform || '';
    }

    //更新账号platform
    async updateAccountPlatform(uid: any, channel_id: any, platform: string, update_time: string) {
        return await query(
            `UPDATE accounts SET platform = ?, updated_at = ? WHERE account = ? AND channel_id = ? AND (platform IS NULL OR platform = '')`,
            [platform, update_time, uid, channel_id]
        );
    }

    //记录登录信息
    async logAccountLogin(
        uid: any,
        login_ip: any,
        device_type: any,
        device_no: any,
        device_model: any,
        device_version: any,
        system_version: string,
        create_time: string,
        channel_id: any,
        platform:  string,
    ) {
        return await query(
            `INSERT INTO account_login_logs(account,login_ip,device_no,device_type,device_version,device_model,
                               system_version,created_at,updated_at,channel_id,platform) VALUES(?,?,?,?,?,?,?,?,?,?,?)`,
            [uid, login_ip, device_no, device_type, device_version, device_model, system_version, create_time, create_time, channel_id,platform]
        );
    }

}

module.exports = new UserModel();
