import { CloudObject, CloudQuery, CloudUser } from './ncloud';

export class CloudSeMealPlan extends CloudObject {
  constructor() {
    super("seMealPlans");
  }

  /** 获取单个饮食规划 */
  async getMealPlan(id: string) {
    const url = `http://dev.fmode.cn:1337/parse/classes/seMealPlans/${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);
  }

  /** 获取当前登录用户的饮食规划信息 */
  async getCurrentUserMealPlan() {
    const cloudUser = new CloudUser();
    const currentUser = await cloudUser.current();

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

    const currentUserId = currentUser.objectId;

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

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

  /** 创建或保存饮食规划信息 */
  async saveMealPlan(mealPlanData: 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 newMealPlan = {
      ...mealPlanData,
      user: userPointer // 将当前用户作为外键关联到 seMealPlans 表
    };

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

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

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

    return this.dataToObj(result);
  }

  /** 更新饮食规划信息 */
  async updateMealPlan(updatedData: Record<string, any>, mealPlanId: string) {
    const mealPlan = new CloudSeMealPlan();
    mealPlan.id = mealPlanId;
    mealPlan.set(updatedData);

    await mealPlan.save(); // 调用 save 方法更新数据
    return mealPlan;
  }

  /** 删除饮食规划 */
  async deleteMealPlan(mealPlanId: string) {
    const mealPlan = new CloudSeMealPlan();
    mealPlan.id = mealPlanId;
    await mealPlan.destroy();

    return true;
  }

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