import { Injectable } from "@nestjs/common"
import { DataSource } from "typeorm"
import { BaseAbstractRepository } from "src/common/repository/base.repository"
import { Notification } from "../entities/notification.entity"

@Injectable()
export class NotificationRepository extends BaseAbstractRepository<Notification> {
  constructor(private dataSource: DataSource) {
    super(dataSource.getRepository(Notification))
  }

  async updateReadStatus(id: number, is_read: boolean) {
    return this.entity.update(id, { is_read })
  }

  async countUnread(user_id: number): Promise<number> {
    return this.entity.count({
      where: { user_id, is_read: false },
    })
  }

  async updateNotificationByUserIdAndTripId(userId: number, tripId: number) {
    return this.entity
      .createQueryBuilder()
      .update()
      .set({ data: null })
      .where(`"notifications"."user_id" = :userId`, { userId })
      .andWhere(`"notifications"."data"::jsonb ->> 'trip_id' = :tripId`, {
        tripId: tripId.toString(),
      })
      .execute()
  }

  async updateNotificationByTripId(tripId: number) {
    return this.entity
      .createQueryBuilder()
      .update()
      .set({ data: null })
      .where(`"notifications"."data"::jsonb ->> 'trip_id' = :tripId`, {
        tripId: tripId.toString(),
      })
      .execute()
  }

  async updateNotificationByTripIdExcludingUser(
    userId: number,
    tripId: number,
  ) {
    return this.entity
      .createQueryBuilder()
      .update()
      .set({ data: null })
      .where(`"notifications"."data"::jsonb ->> 'trip_id' = :tripId`, {
        tripId: tripId.toString(),
      })
      .andWhere(`"notifications"."title" = :title`, {
        title: "New Trip Request",
      })
      .andWhere(`"notifications"."user_id" != :excludedUserId`, {
        excludedUserId: userId,
      })
      .execute()
  }
}
