import { CloudUser, CloudObject, CloudQuery } from './ncloud'; // 引入 CloudUser 类，用于获取当前用户

export class CloudSeUser extends CloudObject {
    constructor() {
        super("seUser"); // 假设 seUser 类在 Parse 中是 "seUser"
    }

    /** 获取单个用户信息 */
    async getUser(id: string) {
        const url = `http://dev.fmode.cn:1337/parse/classes/seUser/${id}?`;

        const response = await fetch(url, {
            headers: {
                "x-parse-application-id": "dev"
            },
            method: "GET",
            mode: "cors",
            credentials: "omit"
        });

        const result = await response?.json();
        if (result?.error) {
            console.error(result?.error);
            return null;
        }

        return this.dataToObj(result);
    }

    /** 获取当前登录用户的 `seUser` 信息 */
    async getCurrentUserInfo() {
        const cloudUser = new CloudUser();
        const currentUser = await cloudUser.current();

        if (!currentUser) {
            console.error("用户未登录");
            return null;
        }

        const currentUserId = currentUser.objectId;

        // 通过 _User 的 objectId 查询 seUser 表中的记录
        const query = new CloudQuery("seUser");
        query.equalTo("user", { "__type": "Pointer", "className": "_User", "objectId": currentUserId });

        const seUser = await query.first();
        return seUser;
    }

    /** 创建或保存用户信息 */
    async saveUserInfo(userData: Record<string, any>) {
        const cloudUser = new CloudUser();
        const currentUser = await cloudUser.current();

        if (!currentUser) {
            console.error("用户未登录");
            return null;
        }

        const userPointer = { "__type": "Pointer", "className": "_User", "objectId": currentUser.objectId };

        const newUserInfo = {
            ...userData,
            user: userPointer // 将当前用户作为外键关联到 seUser 表
        };

        const url = `http://dev.fmode.cn:1337/parse/classes/seUser`;

        const response = await fetch(url, {
            headers: {
                "Content-Type": "application/json",
                "x-parse-application-id": "dev"
            },
            method: "POST",
            body: JSON.stringify(newUserInfo),
            mode: "cors",
            credentials: "omit"
        });

        const result = await response?.json();
        if (result?.error) {
            console.error(result?.error);
            return null;
        }

        return this.dataToObj(result);
    }

    /** 更新当前用户的信息 */
    async updateUserInfo(updatedData: Record<string, any>) {
        const cloudUser = new CloudUser();
        const currentUser = await cloudUser.current();

        if (!currentUser) {
            console.error("用户未登录");
            return null;
        }

        const currentUserId = currentUser.objectId;

        // 查找当前用户的 seUser 信息
        const query = new CloudQuery("seUser");
        query.equalTo("user", { "__type": "Pointer", "className": "_User", "objectId": currentUserId });

        const seUser = await query.first();
        if (!seUser) {
            console.error("未找到用户信息");
            return null;
        }

        // 更新信息
        seUser.set(updatedData);
        await seUser.save();

        return seUser;
    }

    /** 删除当前用户的 seUser 信息 */
    async deleteUserInfo() {
        const cloudUser = new CloudUser();
        const currentUser = await cloudUser.current();

        if (!currentUser) {
            console.error("用户未登录");
            return false;
        }

        const currentUserId = currentUser.objectId;

        // 查找当前用户的 seUser 信息
        const query = new CloudQuery("seUser");
        query.equalTo("user", { "__type": "Pointer", "className": "_User", "objectId": currentUserId });

        const seUser = await query.first();
        if (!seUser) {
            console.error("未找到用户信息");
            return false;
        }

        // 删除 seUser 记录
        await seUser.destroy();

        return true;
    }

    /** 将查询结果转换为 CloudObject */
    private dataToObj(result: any): CloudObject {
        let userObject = new CloudObject(this.className);
        userObject.set(result);
        userObject.id = result.objectId;
        userObject.createdAt = result.createdAt;
        userObject.updatedAt = result.updatedAt;
        return userObject;
    }
}
