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

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

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

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

  async updateNotificationByCustomerIdAndTripId(
    customerId: number,
    tripId: number,
  ) {
    return this.entity
      .createQueryBuilder("notification")
      .update()
      .set({ data: null })
      .where("notification.customer_id = :customer_id", { customerId })
      .andWhere("notification.data::jsonb ->> 'trip_id' = :tripId", { tripId })
      .andWhere("notification.data::jsonb ->> 'trip_id' = :tripId", {
        tripId: tripId.toString(),
      })
      .execute()
  }

  async updateNotificationByTripIdExcludingCustomer(
    customerId: number,
    tripId: number,
  ) {
    return this.entity
      .createQueryBuilder("notification")
      .update()
      .set({ data: null })
      .where("notification.data::jsonb ->> 'trip_id' = :tripId", {
        tripId: tripId.toString(),
      })
      .where("notification.title = :title", { title: "New Trip Request" })
      .andWhere("notification.customer_id != :excludedCustomerId", {
        excludedCustomerId: customerId,
      })
      .execute()
  }
}
