import { CaldavConfig } from "@calchat/shared";
import { Logged } from "../../logging/Logged";
import { CaldavRepository } from "../../services/interfaces/CaldavRepository";
import { CaldavConfigModel } from "./models/CaldavConfigModel";

@Logged("MongoCaldavRepository")
export class MongoCaldavRepository implements CaldavRepository {
  async findByUserId(userId: string): Promise<CaldavConfig | null> {
    const config = await CaldavConfigModel.findOne({ userId });
    if (!config) return null;
    return config.toJSON() as unknown as CaldavConfig;
  }

  async createOrUpdate(config: CaldavConfig): Promise<CaldavConfig> {
    const caldavConfig = await CaldavConfigModel.findOneAndUpdate(
      { userId: config.userId },
      config,
      {
        upsert: true,
        new: true,
      },
    );
    // NOTE: Casting required because Mongoose's toJSON() type doesn't reflect our virtual 'id' field
    return caldavConfig.toJSON() as unknown as CaldavConfig;
  }

  async deleteByUserId(userId: string): Promise<boolean> {
    const result = await CaldavConfigModel.findOneAndDelete({ userId });
    return result !== null;
  }
}
