import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { FindOptionsOrder, Repository } from 'typeorm';
import { ClsService } from 'nestjs-cls';
import { TenantAwareRepository } from '../../../common/repositories/tenant-aware.repository';
import {
  ActivityTicketItemEntity,
  TicketItemStatus,
} from '../../../entities/activity-ticket-item.entity';

@Injectable()
export class ActivityTicketItemRepository extends TenantAwareRepository<ActivityTicketItemEntity> {
  constructor(
    @InjectRepository(ActivityTicketItemEntity) repo: Repository<ActivityTicketItemEntity>,
    cls: ClsService,
  ) {
    super(repo, cls);
  }

  async findAvailableInBatch(batchId: string): Promise<ActivityTicketItemEntity | null> {
    const tenantId = this.getTenantId();
    return this.repo.findOne({
      where: {
        batch_id: batchId,
        tenant_id: tenantId,
        status: TicketItemStatus.AVAILABLE,
        is_deleted: false,
      },
      order: { ticket_ref_no: 'ASC' } as FindOptionsOrder<ActivityTicketItemEntity>,
    });
  }

  async findByBookingActivityItem(
    bookingActivityItemId: string,
  ): Promise<ActivityTicketItemEntity[]> {
    const tenantId = this.getTenantId();
    return this.repo.find({
      where: {
        booking_activity_item_id: bookingActivityItemId,
        tenant_id: tenantId,
        is_deleted: false,
      },
      relations: {
        batch: true,
      },
    });
  }

  async countByBatchAndStatus(batchId: string, status: TicketItemStatus): Promise<number> {
    const tenantId = this.getTenantId();
    return this.repo.count({
      where: { batch_id: batchId, tenant_id: tenantId, status, is_deleted: false },
    });
  }
}
